嗨,我正在尝试从对象数组和其他对象中为海关最终对象创建一个对象(代码中的示例)。我尝试在数组上执行 forEach 并创建一个新对象并将其推送到最终数组,但没有成功。 snapObj
中的数字可能不是 dataArr
中对象中的第一个数字(digit0 可能是 digital1...),这使我很难找到正确的数字一并根据需要表示。有什么建议吗?
var dataArr = {};
//First array of objects
var arrayContactsWithNames = [{
"digits0": "5555648583",
"digits1": "4155553695",
"name": "Kate Bell",
}, {
"digits0": "5554787672",
"digits1": "4085555270",
"digits2": "4085553514",
"name": "Daniel Higgins Jr.",
}, {
"digits0": "8885555512",
"digits1": "8885551212",
"name": "John Appleseed",
}, {
"digits0": "5555228243",
"name": "Anna Haro",
}, {
"digits0": "5557664823",
"digits1": "7075551854",
"name": "Hank M. Zakroff",
}, {
"digits0": "5556106679",
"name": "David Taylor",
}];
// Second object
var snapObj = {
"5556106679": "test 1",
"7075551854": "test 2",
"8885551212": "test 1"
};
/* This is what I want to get:
var dataArr = [{
"test 1": {
"5556106679": "David Taylor",
"8885551212": "John Appleseed"
}
}, {
"test 2": Object {
"7075551854": "Hank M. Zakroff",
}
}]
*/
// This is what I tried
arrayContactsWithNames.forEach((i) => {
if (i in snapObject) {
const newObj = Object.assign({snapObject[i],{ name },{digits${i}}});
dataArr.push(newObj);
}
});
最佳答案
逻辑是首先创建一个 number:name
形式的对象字典,并使用它来查找第二个对象。这是最优的,因为在对象中查找键只需要 O(1)。
var arrayContactsWithNames = [{
"digits0": "5555648583",
"digits1": "4155553695",
"name": "Kate Bell",
}, {
"digits0": "5554787672",
"digits1": "4085555270",
"digits2": "4085553514",
"name": "Daniel Higgins Jr.",
}, {
"digits0": "8885555512",
"digits1": "8885551212",
"name": "John Appleseed",
}, {
"digits0": "5555228243",
"name": "Anna Haro",
}, {
"digits0": "5557664823",
"digits1": "7075551854",
"name": "Hank M. Zakroff",
}, {
"digits0": "5556106679",
"name": "David Taylor",
}];
var snapObj = {
"5556106679": "test 1",
"7075551854": "test 2",
"8885551212": "test 1"
};
let parsedArr = arrayContactsWithNames.reduce((acc,{name,...digits}) => {
Object.values(digits).forEach(digit => { acc[digit] = name });
return acc;
}, {}); // create a { number : name } mapping with some es6 magic. Refer Object destructuring and spread operator to know how the digit0,digit1 etc are extracted.
// console.log(parsedArr)
let parsedObj = Object.keys(snapObj).reduce((acc,num) => {
let val = snapObj[num]
if(!acc[val])
acc[val] = {}
acc[val][num] = parsedArr[num]; // use the lookup object with the number
return acc;
},{}); // A simple reducer to create a new object in the desired shape.
console.log(parsedObj);
关于javascript - 根据以下数据创建自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54577871/