首页 > 解决方案 > 如何在javascript中从内部JSON数组创建具有一些属性的数组

问题描述

所以我有 :

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

我想只使用 arr 数组中的 description 和 author 属性创建一个数组。

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

标签: javascriptnode.jsarraysjsontypescript

解决方案


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

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);


推荐阅读