我正在寻找一种方法来合并JSON对象,如果他们有相同的address
值在他们。建立在这个Combining JSON Question我有这两个样本JSON
文件。会喜欢任何建议,谢谢你这么多。
合并前:
[
{
"saleNo": "86131",
"address": "6562 Dagmar Haven Suite 593 Warner Robins WI, 68085-5440",
"deliveryTo": "Earl Bruen"
},
{
"saleNo": "82483",
"address": "6562 Dagmar Haven Suite 593 Warner Robins WI, 68085-5440",
"deliveryTo": "Harold Kuhn"
},
{
"saleNo": "53731",
"address": "33194 Royal Track Suite 501 Enid CO, 57355",
"deliveryTo": "Kristopher Bayer"
},
{
"saleNo": "12285",
"address": "183 Lazaro Meadow Suite 841 Council Bluffs AL, 52499",
"deliveryTo": "Cassandra Mueller"
},
{
"saleNo": "23404",
"address": "89319 Witting Green Suite 924 Portland MN, 74633-9170",
"deliveryTo": "Chris Thiel Sr."
},
{
"saleNo": "70528",
"address": "2410 Zaria Forges Suite 936 St. Louis GA, 94962-5376",
"deliveryTo": "Glenda Larson"
}
]
合并后:
[
{
"saleNo": ["86131", "82483"],
"address": "6562 Dagmar Haven Suite 593 Warner Robins WI, 68085-5440",
"deliveryTo": ["Harold Kuhn", "Earl Bruen"]
},
{
"saleNo": "53731",
"address": "33194 Royal Track Suite 501 Enid CO, 57355",
"deliveryTo": "Kristopher Bayer"
},
{
"saleNo": "12285",
"address": "183 Lazaro Meadow Suite 841 Council Bluffs AL, 52499",
"deliveryTo": "Cassandra Mueller"
},
{
"saleNo": "23404",
"address": "89319 Witting Green Suite 924 Portland MN, 74633-9170",
"deliveryTo": "Chris Thiel Sr."
},
{
"saleNo": "70528",
"address": "2410 Zaria Forges Suite 936 St. Louis GA, 94962-5376",
"deliveryTo": "Glenda Larson"
}
]
样品代码:
let data = [
{
"saleNo": "86131",
"address": "6562 Dagmar Haven Suite 593 Warner Robins WI, 68085-5440",
"deliveryTo": "Earl Bruen"
},
{
"saleNo": "82483",
"address": "6562 Dagmar Haven Suite 593 Warner Robins WI, 68085-5440",
"deliveryTo": "Harold Kuhn"
},
{
"saleNo": "53731",
"address": "33194 Royal Track Suite 501 Enid CO, 57355",
"deliveryTo": "Kristopher Bayer"
},
{
"saleNo": "12285",
"address": "183 Lazaro Meadow Suite 841 Council Bluffs AL, 52499",
"deliveryTo": "Cassandra Mueller"
},
{
"saleNo": "23404",
"address": "89319 Witting Green Suite 924 Portland MN, 74633-9170",
"deliveryTo": "Chris Thiel Sr."
},
{
"saleNo": "70528",
"address": "2410 Zaria Forges Suite 936 St. Louis GA, 94962-5376",
"deliveryTo": "Glenda Larson"
}
]
let result = Object.values(data.reduce((c, {address,numbers}) => {
c[address] = c[address] || {address,numbers: []};
c[address].numbers = c[address].numbers.concat(Array.isArray(numbers) ? numbers : [numbers]);
return c;
}, {}));
console.log(result);
2条答案
按热度按时间xsuvu9jc1#
此解决方案使用:
对于大型数据集,这种reduce和map解决方案比嵌套for循环方法更快,例如O(2n)vs. O(n*n)
c0vxltue2#
那么
没有做任何聪明的事情?结果并不完全是预期的结果,因为
1.字段
saleNo
和deliveryTo
总是Array
,即使只有一个值--你可以在第一次添加一个字符串时修改这个例子,如果它不是undefined
,检查它是否是Array
,然后简单地添加新值,或者用包含第一个值的Array
替换字符串。但是很容易阅读/跟踪正在发生的事情。当然,问题是在阅读result
时,您必须再次处理此差异,而不是总是有一个Array
。