简体   繁体   English

如何使用reduce获取列表数组对象的一些道具

[英]How to get some props of list array object by using reduce

I have list array object like:我有列表数组对象,如:

let arr = [
    { a: 1, b: 2, c: 3, d: 4 },
    { a: 2, b: 3, c: 4, d: 5 },
    { a: 5, b: 6, c: 7, d: 8 }
]

and after using reduce()并在使用 reduce() 之后

// get props **b, c**
let arr_result = arr.reduce( ... )

// arr_result = [
//    { b: 2, c: 3 },
//    { b: 3, c: 4 },
//    { b: 6, c: 7 }
// ]

use map .使用map

 let arr = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }, { a: 5, b: 6, c: 7, d: 8 } ] const output = arr.map(({b, c}) => ({b, c})); console.log(output);

You can use ES6(and beyond)'s object destructuring .您可以使用 ES6(及更高版本)的object destructuring

 const arr = [ { a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }, { a: 5, b: 6, c: 7, d: 8 } ] const res = arr.map(obj => { const { b, c } = obj; return { b, c }; }); console.log(res);

Since you asked to achieve this using reduce, here is the way.由于您要求使用reduce来实现这一点,因此这是方法。 Pass an empty array as thisArg & inside reduce callback function create an object with required key and push it to the accumulator传递一个空数组作为thisArg & 在 reduce 回调函数中创建一个具有所需键的对象并将其推送到累加器

 let arr = [{ a: 1, b: 2, c: 3, d: 4 }, { a: 2, b: 3, c: 4, d: 5 }, { a: 5, b: 6, c: 7, d: 8 } ]; let newArr = arr.reduce(function(acc, curr) { acc.push({ b: curr.b, c: curr.c }) return acc; }, []) console.log(newArr)

If you want to use reduce :如果你想使用reduce

 const arr = [{a:1,b:2,c:3,d:4},{a:2,b:3,c:4,d:5},{a:5,b:6,c:7,d:8}]; const res = arr.reduce((a, { b, c }) => (a.push({ b, c }), a), []); console.log(res);
 .as-console-wrapper { max-height: 100% !important; top: auto; }

It's honestly a lot easier with map :老实说,使用map容易map

 const arr = [{a:1,b:2,c:3,d:4},{a:2,b:3,c:4,d:5},{a:5,b:6,c:7,d:8}]; const res = arr.map(({ b, c }) => ({ b, c })); console.log(res);
 .as-console-wrapper { max-height: 100% !important; top: auto; }

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

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