Construct an array of objects using another array of objects and a single object

76 views Asked by At

I have an array of object like this:

channels=[
  {name: mega, status: true},
  {name: ant, status: false},
  {name: apl, status: true}
]

and I have a single object with this format

obj = {0: false, 1: true}

The keys in the plain object represent indexes of the channels array. The status properties must be updated.

For the above example data channels should be updated to:

channels=[
  {name: mega, status: false},
  {name: ant, status: true},
  {name: apl, status: true}
]

How can I implement this efficiently?

4

There are 4 answers

4
P.S. On BEST ANSWER

You can iterate through the obj with any method you like (here I used Object.keys to get an array of keys from obj object and forEach to iterate through them) and update the field. It can be achieved in one line of code:

const channels = [
  {name: "mega", status: true},
  {name: "ant", status: false},
  {name: "apl", status: true}
];

const obj = {
  "0": false,
  "1": true
};

Object.keys(obj).forEach((item, i) => channels[i].status = obj[i]);

/**
 * If "channels" array is NOT ALWAYS longer than the amount of "obj" properties,
 * you should add the check for existence, the simpliest one is implemented below:
 * 
 * Object.keys(obj).forEach((item, i) => channels[i] ? channels[i].status = obj[i] : null);
 */
console.log(channels);

In the provided case, the original array is mutated, and if it's not what you need, I recommend to take a look at map method, it doesn't mutate the original array, it creates a new one instead.

0
trincot On

A simple for loop will do:

for (let index in obj) channels[index].status = obj[index];

const channels=[{name: "mega", status: true}, {name: "ant", status: false}, {name: "apl", status: true}];

const obj={0: false, 1:true};

for (let index in obj) {
 channels[index].status = obj[index];
}

console.log(channels);

If you don't want to mutate the original array, but want a new array with the modifications then:

const channels=[{name: "mega", status: true}, {name: "ant", status: false}, {name: "apl", status: true}];

const obj={0: false, 1:true};

const result = channels.map(({name, status}, i) => 
    ({name, status: i in obj ? obj[i] : status})
);

console.log(result);

0
Abdul Aleem On

This loop should do it.

 for(var key in obj){
       channels[key].status = obj[key]
    }
2
Mohammad Usman On

You can iterate over channels array using forEach() and use Object.assign() to override property.

let channels = [
  {name: 'mega', status: true },
  {name: 'ant' , status: false},
  {name: 'apl' , status: true }
];

let obj = {
  0: false,
  1: true
};

channels.forEach((o, i) => i in obj ? Object.assign(o, {status: obj[i]}) : o);

console.log(channels);
.as-console-wrapper { max-height: 100% !important; top: 0; }