gpt4 book ai didi

javascript - 合并具有相同第一个键值的对象,因此其余键值将添加到合并对象中

转载 作者:行者123 更新时间:2023-12-01 01:12:17 26 4
gpt4 key购买 nike

您好,我在任何地方都找不到问题的答案。

我在创造什么?

我正在创建数据库管理面板,前面是 vue.js,后面是 node.js + mySQL。

有 4 个数据库。每个数据库行都有 phone_numbere_mailcreatedsource_website 列。

我已经从所有数据库导入了记录。我将它们放入一个对象数组中。

我想要实现什么目标?

我想合并具有同一电子邮件地址的记录,并将每个重复记录中的每个值推送到一个合并记录。

预期输出

之前:

[
{
"number": "111111111",
"email": "test@test.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://firstwebsite.com",
"id": 24,
},
{
"number": "111222222",
"email": "test@test.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://secondwebsite.com",
"id": 24,
},
]

之后:

[
{
"number": "111111111, 111222222",
"email": "test@test.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://firstwebsite.com, http://secondwebsite.com",
"id": 24,
},
]

最佳答案

这可能会被简化,但它正在起作用。

let data = [{
"number": "111111111",
"email": "test@test.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://firstwebsite.com",
"id": 24,
}, {
"number": "452",
"email": "stack@overflow.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://first.com",
"id": 28,
}, {
"number": "111222222",
"email": "test@test.com",
"created": "2019-02-18T15:01:18.000Z",
"website": "http://secondwebsite.com",
"id": 24,
}, {
"number": "999",
"email": "stack@overflow.com",
"created": "2019-05-18T15:01:18.000Z",
"website": "http://first.com",
"id": 29,
}];

// Start with an object because I will use email property as key
// for an easier checking of which email has already been looped through
let result = {};

for (let i in data) {
let item = data[i],
// Here the checking that I talked above
toPush = (result[item.email]) ? result[item.email] : {};

for (let property in item) {
let value = item[property];

if (!toPush[property]) {
toPush[property] = value;
} else {
// If the current value is not already in the value list,
// we add it after a ", "
if (`${toPush[property]}`.indexOf(value) === -1) {
toPush[property] += `, ${value}`;
}
}
}

result[item.email] = toPush;
}

// As we want an array as final result
result = Object.values(result);

console.log(result);

关于javascript - 合并具有相同第一个键值的对象,因此其余键值将添加到合并对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55064369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com