Home > Back-end >  Update an array of objects using another array
Update an array of objects using another array

Time:10-24

i need to update the array of objects based on another array in ES6. Example

let a = [ 
  { id : 23, active :false },
  { id : 33, active :false },
  { id : 167, active :false },
  { id : 18, active :false },
  { id : 2, active :false },
]

my second array which contain the objects

let marked = [167,33,23];

expected results as below

let a = [ 
  { id : 23, active :true},
  { id : 33, active :false },
  { id : 167, active :true },
  { id : 18, active :true },
  { id : 2, active :false },
]

please let me know how to get as expected result. do we have any other methods in lodash for this.?

CodePudding user response:

You don't need lodash, you could do this:

let a = [{
        id: 23,
        active: false
    },
    {
        id: 33,
        active: false
    },
    {
        id: 167,
        active: false
    },
    {
        id: 18,
        active: false
    },
    {
        id: 2,
        active: false
    },
]

let marked = [167, 33, 23];

let result = a.map(x => ({
    ...x,
    active: marked.includes(x.id)
}))
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can make this faster if you go over the marked array and store its elements in an object. Then during the map checking if element x.id is inside the object will be faster (vs checking inside array). But in practice in most of the cases you should not notice the difference.

CodePudding user response:

Try with this, use map function with includes function. Hope so this answer gives your actual result. if not then comment to me I'll give you another answer.

const found = a.map(function(mapData){
    (marked.includes(mapData.id)) ? mapData.active = true : '';
    return mapData;
})
  • Related