问题
I have an array of object, within those objects is a name
property.
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
I’m collecting an array of strings from an outside source containing names.
const strArr = [ "Avram", "Andy", "Brandon" ];
If strArr
contains a string that does not exist as a property name
on an object in objArr
, I need to create a new object and push it to objArr
.
For example: objArr.push( { name: "Brandon" } );
Obviously, I can use nested loops, but I’d like to avoid that if possible. What is the best way to do this programmatically?
回答1:
like this
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);
回答2:
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);
回答3:
Map
objArr
to same structure as strArr
. Then concat
the 2 arrays. Run it through a Set
to remove duplicates, then remap
to correct array of object
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);
回答4:
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);
来源:https://stackoverflow.com/questions/47465037/best-way-to-compare-an-array-of-strings-to-an-array-objects-with-string-properti