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?
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);
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);
Map
objArr
to same structure as strArr
. Then concat
the 2 arrays. Run it through a Set
to remove duplicates, then re map
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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.