【问题标题】:Assign First Element of Nested Array as Property of Parent Object将嵌套数组的第一个元素分配为父对象的属性
【发布时间】:2017-07-11 15:24:25
【问题描述】:

假设如下数组:

[
{id: 1234, name: "@Acme", sources:["Twitter"]},
{id: 5678, name: "@Enron", sources:["Facebook"]},
]

我想将sources[0] 提升为属性值,可以在源本身下,也可以使用lodash 作为新键。

我做了以下事情:

myList = _.map(monitorList, _.partialRight(_.pick, ['id', 'name', 'sources']));
mySources = _.map(monitorList, 'sources');

我想我现在可以遍历每个相应的数组并将我的索引从 mySources 映射到 myList 中的源键,但是似乎应该有一种使用 lodash 将嵌套数组项提升为属性值。

理想的最终数据结构:

[
{id: 1234, name: "@Acme", sources:"Twitter"},
{id: 5678, name: "@Enron", sources:"Facebook"},
]

【问题讨论】:

  • 您能否也显示您想要实现的预期输出结构?
  • @guwere 更新了更多细节

标签: javascript ecmascript-6 lodash


【解决方案1】:

使用函数式 ES6 方法:

const monitorList = [
    {id: 1234, name: "@Acme", sources:["Twitter"]},
    {id: 5678, name: "@Enron", sources:["Facebook"]},
];

var result = monitorList.map(o => Object.assign({}, o, { sources: o.sources[0] }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    您可以按照简单的路径,使用forEach 替换sources 属性:

    var items = [{id: 1234, name: "@Acme", sources:["Twitter"]},
                 {id: 5678, name: "@Enron", sources:["Facebook"]}];
    
    items.forEach((item) => item.sources = item.sources[0]);
    
    console.log(items);

    另一种解决方案,使用map,它更实用(因为它不会更改items 变量):

    var items = [{id: 1234, name: "@Acme", sources:["Twitter"]},
                 {id: 5678, name: "@Enron", sources:["Facebook"]}];
    
    var newItems = items.map((item) => Object.assign({}, item, { sources: item.sources[0] }));
    
    console.log(newItems);

    【讨论】:

    • 请注意,这样做会改变原始数组。这可能没问题,但它不是很实用。
    • @terpinmd。确实如此。编辑我的答案以包含更实用的解决方案。谢谢!
    • 我想在lodash 中得到答案,但它非常相似,在这种情况下我不关心原始数组的突变,所以你的解决方案让我走上了正确的道路:_.forEach(monitorList, monitor => monitor.sources = monitor.sources[0]);
    • 是的,_.forEach 最终等同于 Array.prototype.forEach
    • @TylerMills,我有点困惑如何调和 “应该有一种功能性的方式”“我不关心突变” i>.
    【解决方案3】:

    你可以使用地图:

    var array = [{id: 1234, name: "@Acme", sources:["Twitter"]},
                  {id: 5678, name: "@Enron", sources:["Facebook"]}];
    
    
    var items = array.map(item => {
      item.source = item.sources[0]; 
      return item;
    });
    

    如果您想覆盖,也可以将 item.source 更改为 item.sources。

    使用一些 losdash 方法的另一种方式:

    var items = array.map(item => {
      return _.assign({}, item, {sources: _.first(item.sources)});
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多