Ric*_*rdS 1 javascript json dictionary object
我已经查看了 SO 中的每个“Merge JSON Objects on Same Key”问题,但无济于事。
我有两个不同长度的 JSON 对象数组,如下所示,我需要合并每个具有共享密钥(在本例中为realName)的 JSON 对象,并转储两者中都没有出现的内容:
let arrObjA = [{
"index": 114,
"realName": 'kevin',
"bucket": 'boss',
"react_name": 'BossKevin'
},
{
"index": 115,
"realName": 'angela',
"bucket": 'boss',
"react_name": 'BossAngela'
},
{
"index": 116,
"realName": 'james',
"bucket": 'janitor',
"react_name": 'JanitorJames'
},
{
"index": 117,
"realName": 'arthur',
"bucket": 'employee',
"react_name": 'EmployeeArthur'
}
]
Run Code Online (Sandbox Code Playgroud)
和
let arrObjB = [{
"boxName": "building",
"realName": "angela",
"boxValue": "2"
},
{
"boxName": "building",
"realName": "james",
"boxValue": "false"
},
{
"boxName": "building",
"realName": "arthur",
"boxValue": "0"
},
]
Run Code Online (Sandbox Code Playgroud)
结果应该是:
let result = [{
"index": 115,
"realName": 'angela',
"bucket": 'boss',
"react_name": 'BossAngela',
"boxName": "building",
"boxValue": "2"
},
{
"index": 116,
"realName": 'james',
"bucket": 'janitor',
"react_name": 'JanitorJames',
"boxName": "building",
"boxValue": "false"
},
{
"index": 117,
"realName": 'arthur',
"bucket": 'employee',
"react_name": 'EmployeeArthur',
"boxName": "building",
"boxValue": "0"
}
]
Run Code Online (Sandbox Code Playgroud)
因此,新数组 ( result) 中的新 JSON 对象是合并的 JSON 对象,其中密钥realName在原始 JSON 对象之间共享(例如arrObjA["realName"] === arrObjB["realName"])。并且realName带有“kevin”的一个 JSON 对象arrObjA不在新数组中,因为该键/值没有出现在两个数组中的 JSON 对象中。
我已经尝试了另一个 SO 答案中的以下内容,这使我最接近我需要的结果(在我尝试过的所有其他几十个答案中),但我只得到一个键/值,因为我没有知道如何扩展对象。
const mappingEngine = (arrA, arrB) => {
const resultsKeys = ["realName", "bucket"];
const result = arrA
.filter(function (o1) {
return arrB.some(function (o2) {
return o1.realName === o2.realName; // assumes unique id
});
})
.map(function (o) {
console.log(o)
return resultsKeys.reduce(function (newo, name) {
newo[name] = o[name];
return newo;
}, {});
});
return result;
};
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助。
您可以使用 es6 spread ( ...) 运算符来分隔两个对象。
let arrObjA = [{ "index": 114, "realName": 'kevin', "bucket": 'boss', "react_name": 'BossKevin' }, { "index": 115, "realName": 'angela', "bucket": 'boss', "react_name": 'BossAngela' }, { "index": 116, "realName": 'james', "bucket": 'janitor', "react_name": 'JanitorJames' }, { "index": 117, "realName": 'arthur', "bucket": 'employee', "react_name": 'EmployeeArthur' }]
let arrObjB = [{ "boxName": "building", "realName": "angela", "boxValue": "2" }, { "boxName": "building", "realName": "james", "boxValue": "false" }, { "boxName": "building", "realName": "arthur", "boxValue": "0" },]
let result = arrObjB.map(item => ({
...arrObjA.find(({ realName }) => item.realName == realName),
...item,
}));
console.log(result)Run Code Online (Sandbox Code Playgroud)