从对象数组中删除键并将值转换为键值对

Remove keys from object array and turn values into key value pairs

我有一个如下所示的数组:

data =
   [{'province': 'North', 'level': 1, 'count': 204},
    {'province': 'South', 'level': 1, 'count': 24},
    {'province': 'East', 'level': 1, 'count': 24},
    {'province': 'West', 'level': 1, 'count': 39}];

我想删除属性级别,并希望将省份值设为键,将计数值设为所需输出的值:

result = 
   {'North':204, 'South':24, 'East':24, 'West':39}

我已经能够通过以下方法删除“level”属性:

let test = _.map(data, function(currentObject) {
    return _.pick(currentObject, "province", "count");
  });

这给了我:

test = 
    [{'province': 'North', 'count': 204},
    {'province': 'South', 'count': 24},
    {'province': 'East', 'count': 24},
    {'province': 'West', 'count': 39}];

我怎样才能达到我想要的结果?

鉴于我了解期望的结果是什么,将数据映射到一个新对象中:

const data =
      [{'province': 'North', 'level': 1, 'count': 204},
       {'province': 'South', 'level': 1, 'count': 24},
       {'province': 'East', 'level': 1, 'count': 24},
       {'province': 'West', 'level': 1, 'count': 39}];

const provinces = data.map(d => ({ [d.province]: d.count }));

console.log(provinces)

这可以通过 Array.reduce():

let data =[
  {'province': 'North', 'level': 1, 'count': 204},
  {'province': 'South', 'level': 1, 'count': 24},
  {'province': 'East', 'level': 1, 'count': 24},
  {'province': 'West', 'level': 1, 'count': 39}
];

let res = data.reduce((acc, curr) =>
{
    acc[curr.province] = curr.count;
    return acc;
}, {});

console.log(res);

一种非常简短的方法是将新对象映射到所需的 属性 并将所有对象分配给单个对象。

var data = [{ province: 'North', level: 1, count: 204 }, { province: 'South', level: 1, count: 24 }, { province: 'East', level: 1, count: 24 }, { province: 'West', level: 1, count: 39 }],
    result = Object.assign({}, ...data.map(({ province, count }) => ({ [province]: count })));

console.log(result);