Home > OS >  check same names in two array of objects in javascript /typescript?
check same names in two array of objects in javascript /typescript?

Time:05-24

I have two array of objects

array1=[{name:'apple',deleted:false},
       {name:'road',deleted:false},
       {name:'tree',deleted:false}]

and

array2=[{name:'apple'},
       {name:'tree'}]

what I want is : if array1 object has same names in array2, I want to change value of "deleted" in array1 to true . eg : {name:'apple',deleted:true}

expecting resulting array1:

array1=[{name:'apple',deleted:true},
           {name:'road',deleted:false},
           {name:'tree',deleted:true}]

here you can see , only apple, tree has deleted=true, because array2 has only 2 names : apple and tree.

CodePudding user response:

you can :

  • loop on array1 with forEach for sample

  • use some function to set deleted boolean

    deleted = array2.some(elem2 => elem2.name === elem.name)
    

const array1 = [{
    name: 'apple',
    deleted: false
  },
  {
    name: 'road',
    deleted: false
  },
  {
    name: 'tree',
    deleted: false
  }
]

const array2 = [{
    name: 'apple'
  },
  {
    name: 'tree'
  }
];

array1.forEach(elem => elem.deleted = array2.some(elem2 => elem2.name === elem.name));

console.log(array1);

CodePudding user response:

Use forEach() to loop array1 and use include() to set value of deleted

const array1=[{name:'apple',deleted:false},
       {name:'road',deleted:false},
       {name:'tree',deleted:false}]
       
const array2=[{name:'apple'},
       {name:'tree'}]
       
array1.forEach(el=> el.deleted = array2.map(foo => foo.name).includes(el.name))
console.log(array1)

CodePudding user response:

  1. Create a Set of deletedItems.

  2. Map over the items and update the deleted property using the Set.

const 
  items = [{ name: "apple", deleted: false }, { name: "road", deleted: false }, { name: "tree", deleted: false }],
  deletedItems = [{ name: "apple" }, { name: "tree" }],
  deletedSet = new Set(deletedItems.map((d) => d.name)),
  updatedItems = items.map((i) => (deletedSet.has(i.name) ? { ...i, deleted: true } : i));

console.log(updatedItems);

CodePudding user response:

You can use Array.map and Array.find:

let array1=[
  {name:'apple',deleted:false},
  {name:'road',deleted:false},
  {name:'tree',deleted:false}
];

let array2=[
  {name:'apple'},
  {name:'tree'}
];

array1 = array1.map(item1 => array2.find(item2 => item1.name == item2.name) ? {...item1, deleted:true} : item1);

console.log(array1)

  • Related