Home > Software engineering >  Use of Object.entries()
Use of Object.entries()

Time:07-22

Is there a way to simplify this code with the use of Object.entries()? I want to remove new Map().

const err = [{ 
 'id': 1, 
 'error': ["Error 1", "Error2"]
}]

const warn = [{ 
 'id': 1, 
 'warning': ["Warn 1", "Warn 2"]
}]

const map = new Map();
err.forEach(item=> map.set(item.id, item));
warn.forEach(item=> map.set(item.id, {...map.get(item.id), ...item}));
const combined = Array.from(map.values());
console.log(combined)

Tried:

const map = new Map(Object.entries(err));
warn.forEach(item=> map.set(item.id, {...map.get(item.id), ...item}));
const combined = Array.from(map.values());
console.log(combined)

The output should still be the same

[{ 
 'id': 1, 
 'error': ["Error 1", "Error2"],
 'warning': ["Warn 1", "Warn 2"] 
}]

CodePudding user response:

You can use Array.prototype.map() to create the key/value pairs for the new Map() argument.

const err = [{
  'id': 1,
  'error': ["Error 1", "Error 2"]
}]

const warn = [{
  'id': 1,
  'warning': ["Warn 1", "Warn 2"]
}]


const map = new Map(err.map(el => [el.id, el]));
warn.forEach(el => map.get(el.id).warning = el.warning);
const combined = Array.from(map.values());
console.log(combined)
Object.entries() isn't useful because the keys are the array indexes, not the id properties.

CodePudding user response:

If you expect more than 1 item per array you can do:

const err = [{ 
 'id': 1, 
 'error': ["Error 1", "Error2"]
}]

const warn = [{ 
 'id': 1, 
 'warning': ["Warn 1", "Warn 2"]
}]


const newObj = err.map( (item,i) => Object.assign({},item,warn[i]));

console.log(newObj)

If the final object depends on those other arrays and you know in advance that they have exactly length 1 then is simpler:

const err = [{ 
 'id': 1, 
 'error': ["Error 1", "Error2"]
}]

const warn = [{ 
 'id': 1, 
 'warning': ["Warn 1", "Warn 2"]
}]


const newArr = [Object.assign({},err[0],warn[0])]

console.log(newArr)

CodePudding user response:

Object entries is for object, not an array. However you can group by using reduce into object, then get his values to turn into array.

const err = [{
  'id': 1,
  'error': ["Error 1", "Error 2"]
}]

const warn = [{
  'id': 1,
  'warning': ["Warn 1", "Warn 2"]
}]


var combined = Object.values(err.concat(warn).reduce(function(agg, item) {
  agg[item.id] = { ...agg[item.id], ...item}
  return agg;
}, {}));
console.log(combined)

  • Related