我有一个对象数组,在这些对象中是name
属性。
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
我正在从包含名称的外部源收集一个字符串数组。
const strArr = [ "Avram", "Andy", "Brandon" ];
如果strArr
包含的字符串在name
中的对象上不作为属性objArr
存在,我需要创建一个新对象并将其推送到objArr
。
例如:objArr.push( { name: "Brandon" } );
显然,我可以使用嵌套循环,但如果可能的话,我想避免使用它。以编程方式执行此操作的最佳方法是什么?
答案 0 :(得分:0)
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const names= objArr.map(x => x.name);
strArr.forEach(str => {
if (! names.includes(str) ) {
objArr.push({name: str});
}
});
console.log(objArr);
答案 1 :(得分:0)
function fillMissing(arr, names) {
names.forEach(name => { // for each name in names
if(arr.every(obj => obj.name !== name)) { // if every object obj in the array arr has a name diferent than this name (this name doesn't exist in arr)
arr.push({name}); // then add an object with that name to arr
}
});
}
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
fillMissing(objArr, strArr);
console.log(objArr);
答案 2 :(得分:0)
Map
objArr
与strArr
的结构相同。然后concat
2个数组。通过Set
运行它以删除重复项,然后重新map
以更正对象数组
const objArr = [ { name: "Avram" }, { name: "Andy" }, { name: "John"} ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const res = Array.from(new Set(objArr.map(i=>i.name).concat(strArr))).map(i=>({name:i}))
console.log(res);

答案 3 :(得分:0)
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const objNamesArr = objArr.map((obj) => obj.name)
strArr.forEach((ele) => objNamesArr.indexOf(ele) == -1 && objArr.push({name:ele}))
console.log('objArr', objArr);
console.log('strArr', strArr);