Setting property of objects in array

问题: I have an array of objects: [{ id: 1, cod: '123', val: true }, { id: 2, cod: '123', val: true }, { id: 3, cod: '123', val: true...

问题:

I have an array of objects:

[{
   id: 1,
   cod: '123',
   val: true      
},
{
   id: 2,
   cod: '123',
   val: true      
},
{
   id: 3,
   cod: '123',
   val: true      
},
{
   id: 4,
   cod: '456',
   val: true      
},
{
   id: 5,
   cod: '456',
   val: true      
}]

I need to maintain the val property true for the objects which have the same cod and have the higher id. For example, I'd need the following output:

[{
   id: 1,
   cod: '123',
   val: false
},
{
   id: 2,
   cod: '123',
   val: false
},
{
   id: 3,
   cod: '123',
   val: true      
},
{
   id: 4,
   cod: '456',
   val: false
},
{
   id: 5,
   cod: '456',
   val: true      
}]

How could I change this array in order to obtain the desired results? Should I use filter? I'm a little lost.


回答1:

You need to process and mutate every element in the array (assuming in-place mutation is fine), so .filter is not suitable here, since it usually just "removes" elements.

A general approach would be: Iterate over every element of the array and keep a cod => previous item map to keep track of the previous item with the same cod value. Set val of the current item to true, set val of the previous item with the same cod value to false, update tracking entry for current item's cod value.

Example:

const data = [{
   id: 1,
   cod: '123',
   val: true      
},
{
   id: 2,
   cod: '123',
   val: true      
},
{
   id: 3,
   cod: '123',
   val: true      
},
{
   id: 4,
   cod: '456',
   val: true      
},
{
   id: 5,
   cod: '456',
   val: true      
}];

const previousCod = new Map();

for (const item of data) {
  if (previousCod.has(item.cod)) {
    previousCod.get(item.cod).val = false;
  }
  // Can be omitted if the initial value is guaranteed to be `true`
  item.val = true;
  previousCod.set(item.cod, item);
}

console.log(data);

  • 发表于 2019-03-02 04:17
  • 阅读 ( 187 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除