如何使用lodash从对象转换为特定的键值对?

时间:2019-02-09 14:36:19

标签: arrays dictionary lodash transform

Products: [
  {_id: 'xx1', name: 'p1', sku: 's1'},
  {_id: 'xx2', name: 'p2', sku: 's2'},
  {_id: 'xx3', name: 'p3', sku: 's3'}
]

我想用'product'替换单词'_id',并映射到以下结果:

productArray = [ {product: 'xx1'}, {product: 'xx2'}, {product: 'xx3'} ];

我尝试了如下类似的破折号代码,但似乎无法正常工作:

let productArray = _.map(Products, '_id');

有人可以帮我吗?谢谢

1 个答案:

答案 0 :(得分:0)

您为什么还要使用lodash? Map可以轻松完成这项工作。

const products = [{
    _id: 'xx1',
    name: 'p1',
    sku: 's1'
  },
  {
    _id: 'xx2',
    name: 'p2',
    sku: 's2'
  },
  {
    _id: 'xx3',
    name: 'p3',
    sku: 's3'
  }
];

const outProducts = products.map(x => {
  return {
    product: x._id
  }
});

console.log(outProducts);

相关问题