慕娘9325324
2022-12-22 14:58:51
假設(shè)我有這兩個(gè)實(shí)體const obj1 = {key1: "", key2: "", key3: ""};const array2 = [ { name: "key1", }]如何檢查是否array2有一個(gè)對(duì)象具有每個(gè)字段的名稱obj1?基本上我想以數(shù)組 2 變成這樣結(jié)束:const array2 = [ { name: "key1", },{ name: "key2", },{ name: "key3", }]
1 回答

慕田峪9158850
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
是這樣的嗎?
const obj1 = {
key1: "",
key2: "",
key3: ""
};
const array2 = [{
name: "key1",
}, {
name: "key2",
}];
const obj1Keys = Object.keys(obj1);
const array2KeyNames = array2.reduce((array2KeyNames, obj) => {
array2KeyNames.push(obj.name);
return array2KeyNames;
}, []);
for (let i = 0; i < obj1Keys.length; i++) {
if (!array2KeyNames.includes(obj1Keys[i])) {
console.log(obj1Keys[i], ' is not in the array2');
break;
}
}
添加回答
舉報(bào)
0/150
提交
取消