【问题标题】:How to create an array with some properties from an inner JSON array in javascript如何在javascript中从内部JSON数组创建具有一些属性的数组
【发布时间】:2021-09-26 20:36:39
【问题描述】:

所以我有:

list = 
    {
      id: 1,
      arr: [
        {index : 1 , description: "lol" , author: "Arthur"},
        {index : 2 , description: "sdadsa" , author: "Bob"},
        {index : 3 , description: "loasd" , author: "Mackenzie"}
      ]
    }

我想创建一个仅包含 arr 数组中的描述和作者属性的数组。

我试过var a = {l : list.arr.map(x => {x.description,x.author})}。但是数组中的所有项目都是未定义的。

【问题讨论】:

  • 你的list 中的arr 不是数组,你确定这里没有错字吗?
  • 谢谢,我编辑了这个问题。这是我正在尝试做的简化版本。
  • 您还有问题吗? @radurbalau
  • 不,我想通了!谢谢大家!

标签: javascript node.js arrays json typescript


【解决方案1】:

您只是忘记在返回对象中定义键。

var list = {
  id: 1,
  arr: [
    { index: 1, description: "lol", author: "Arthur" },
    { index: 2, description: "sdadsa", author: "Bob" },
    { index: 3, description: "loasd", author: "Mackenzie" },
  ],
};

var a = l.arr.map(x => ({
  description: x.description,
  author: x.author,
}));

【讨论】:

    【解决方案2】:

    另一种方法是使用rest parameter。这样您就可以删除索引并保持其他所有内容不变。

    var list = {
      id: 1,
      arr: [
        { index: 1, description: "lol", author: "Arthur" },
        { index: 2, description: "sdadsa", author: "Bob" },
        { index: 3, description: "loasd", author: "Mackenzie" },
      ],
    };
    
    var a = list.arr.map(({index, ...rest}) => rest);
    
    console.log(a);

    【讨论】:

    • 哇,太棒了!惊人的想法!
    【解决方案3】:

    list = {
      id: 1,
      arr: [{
          index: 1,
          description: "lol",
          author: "Arthur"
        },
        {
          index: 2,
          description: "sdadsa",
          author: "Bob"
        },
        {
          index: 3,
          description: "loasd",
          author: "Mackenzie"
        }
      ]
    }
    
    var a = {
      l: list.arr.map(x => ({
        "description": x.description,
        "author": x.author
      }))
    }
    console.log(a);

    【讨论】:

      【解决方案4】:

      你差不多完成了,你应该在 map 函数的返回对象中定义键。

      var list = {
        id: 1,
        arr: [
          { index: 1, description: "lol", author: "Arthur" },
          { index: 2, description: "sdadsa", author: "Bob" },
          { index: 3, description: "loasd", author: "Mackenzie" },
        ],
      };
      
      var a = list.arr.map(x => ({
        description: x.description,
        author: x.author,
      }));
      
      console.log(a);

      【讨论】:

      • 所以错误是当我返回地图时我没有将 () 包裹到对象上?
      • @radurbalau,是的。此外,您还应该定义对象的键。
      猜你喜欢
      • 2022-07-29
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多