简体   繁体   English

如何从javascript中的内部JSON数组创建具有某些属性的数组

[英]How to create an array with some properties from an inner JSON array in javascript

So I have :所以我有 :

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

and I want to create an array only with description and author property from the arr array.我想创建一个仅包含来自 arr 数组的 description 和 author 属性的数组。

I tried var a = {l : list.arr.map(x => {x.description,x.author})} .我试过var a = {l : list.arr.map(x => {x.description,x.author})} But all items from the array are undefined .但是数组中的所有项目都是 undefined 。

Another approach would be to use the rest parameter .另一种方法是使用rest 参数 This way you can remove the index and keep everything else intact.通过这种方式,您可以删除索引并保持其他所有内容完好无损。

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

You almost finish, you should define the key in your return object in the map funciton.你快完成了,你应该在地图函数的返回对象中定义键。

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

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

You just forget to define keys in return object.您只是忘记在返回对象中定义键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM