【问题标题】:How to get transform from object to specific key value pair using lodash?如何使用 lodash 从对象转换为特定的键值对?
【发布时间】:2019-02-09 14:36:19
【问题描述】:
Products: [
  {_id: 'xx1', name: 'p1', sku: 's1'},
  {_id: 'xx2', name: 'p2', sku: 's2'},
  {_id: 'xx3', name: 'p3', sku: 's3'}
]

我想用“产品”替换单词“_id”,并映射到以下结果:

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

我尝试了类似下面的 lodash 代码,但它似乎无法正常工作:

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

谁能帮我解决这个问题?谢谢

【问题讨论】:

    标签: arrays dictionary lodash transform


    【解决方案1】:

    为什么你甚至需要使用 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-25
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 2019-04-18
      • 2015-07-25
      相关资源
      最近更新 更多