简体   繁体   中英

How to filter an Array and Replace some values out of it

For Example I have this Array:

 const mainArray = [
   {name: 'Tom', age: 33, status: 0 }, 
   {name: 'James', age: 23, status: 0}, 
   {name: 'Bryan', age: 34, status:1 }  
 ] 

and then I have this 2nd Array

 const toUpdateStatus = ['Tom', 'James'] 

the expected value of the Array should be like this after merging the two

   const finalValue = [
       {name: 'Tom', age: 33, status: 1 }, 
       {name: 'James', age: 23, status: 1}, 
       {name: 'Bryan', age: 34, status:0 }  
     ] 

what I have tried so far is this

const result = toUpdateStatus.map((checked) => mainArray.filter((val) => val.name.includes(checked)));

but to no luck

Return an object from the .map immediately, with a status property of whether the name is included in the toUpdateStatus , converted to a number:

 const mainArray = [ {name: 'Tom', age: 33, status: 0 }, {name: 'James', age: 23, status: 0}, {name: 'Bryan', age: 34, status:1 } ] const toUpdateStatus = ['Tom', 'James']; const output = mainArray.map(({ name, age }) => ({ name, age, status: Number(toUpdateStatus.includes(name)) })); console.log(output);

You can quickly make a Map of the toUpdateStatus using the names as values and status as 1. Then array map the original and get() status from the lookup Map or set as zero if not existing.

This way neither array gets iterated more than once.

 const mainArray = [{name: 'Tom', age: 33, status: 0 }, {name: 'James', age: 23, status: 0}, {name: 'Bryan', age: 34, status: 1 }] ; const toUpdateStatus = ['Tom', 'James']; const stats = new Map(toUpdateStatus.map(name => [name, 1])); const res = mainArray.map(el => ({...el, status: stats.get(el.name) || 0})) console.log(res)
 

Similar to some other answers, but makes no assumptions about the fields in your objects except that they have a name property:

 const updateStatus = (main, names) => main .map ( ({name, ...o}) => ({name, ...o, status: Number(names .includes (name))}) ) const mainArray = [{name: 'Tom', age: 33, status: 0 }, {name: 'James', age: 23, status: 0}, {name: 'Bryan', age: 34, status: 1 }] const toUpdateStatus = ['Tom', 'James'] console .log (updateStatus (mainArray, toUpdateStatus))
 .as-console-wrapper {min-height: 100% !important; top: 0}

  1. Map-index for main array:
var map = {};
mainArray.forEach(v=>map[v.name] = v);
//OR
var map = mainArray.reduce((s,v)=>(s[v.name] = v, s), {});
  1. Reset records:
mainArray.forEach(v=>v.status = 0);
  1. Update records:
toUpdateStatus.forEach(v=>map[v].status = 1);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM