我有一个对象数组,需要遍历并检查对象的键是否具有不同的值。如果是这样,请返回此 key 。
const arrayOfObjects = [
{ item: { first_name: "Joe", last_name: "Dow", age: 15 } },
{ item: { first_name: "Joe", last_name: "d", age: 15 } },
{ item: { first_name: "Joe", last_name: "Dow", age: 20 } }
];
预期结果应该是
const result = {
last_name: true,
age: true
}
PS:每个对象总是有相同数量的键
最佳答案
您可以遍历 arrayOfObjects
。检查当前 item
的键与之前对象的 item
相比是否具有不同的值。如果是,请在 result
true
const arrayOfObjects = [{ item: { first_name: "Joe", last_name: "Dow", age: 15 } }, { item: { first_name: "Joe", last_name: "d", age: 15 } }, { item: { first_name: "Joe", last_name: "Dow", age: 20 } }];
const result = {};
arrayOfObjects.forEach(({ item }, i, arr) => {
if (i === 0) return; // skip the first item
const prev = arr[i - 1].item; // get the previous item
for (const key in item) {
if (item[key] !== prev[key])
result[key] = true
}
})
console.log(result)
关于Javascript 遍历对象数组并返回一个对象,该对象仅包含其值已更改的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466000/