[英]How can I extract pin property from an object and make an array of pins in JavaScript?
I have done it with array PinArray.push(data.pin)
, but I am looking for a better solution.我已经用数组PinArray.push(data.pin)
完成了它,但我正在寻找更好的解决方案。
let PinArray = [];
const bbb = AllPackages.forEach(p => {
p.dealProducts
.filter(dp => dp.product.code === 'AAA')
.forEach(data => PinArray.push(data.pin));
});
const AllPackages = [ { Id: 1, dealProducts: [ { pin: 'AAA000', product: { id: '100', code: 'AAA', name: 'AAA' } }, { pin: 'AAA111', product: { id: '200', code: 'BBB', name: 'BBB' } } ] }, { Id: 2, dealProducts: [ { pin: '', product: { id: '300', code: 'CCC', name: 'CCC' } }, { pin: '1', product: { id: '200', code: 'AAA', name: 'BBB' } }, { pin: '1', product: { id: '200', code: 'BBB', name: 'BBB' } }, { pin: '', product: { id: '400', code: 'DDD', name: 'DDD' } }, { pin: 'AAA111', product: { id: '100', code: 'AAA', name: 'AAA' } } ] } ]; const PinArray = AllPackages.forEach(p => { p.dealProducts.filter(dp => dp.product.code === 'AAA').forEach(data => { const{pin} = data; return pin; }); }); console.log(PinArray); <:-- begin snippet: js hide: false console: true babel: false -->
You can concisely get a single array of all the dealProducts
with flatMap
.您可以使用flatMap
简洁地获取所有dealProducts
的单个数组。 Then .filter
to select only those with the right code, then map to extract the pin from each:然后.filter
到 select 只有那些具有正确代码的,然后 map 从每个提取引脚:
const pinArray = AllPackages
.flatMap(p => p.dealProducts)
.filter(obj => obj.product.code === 'AAA')
.map(data => data.pin);
const AllPackages = [{ Id: 1, dealProducts: [{ pin: 'AAA000', product: { id: '100', code: 'AAA', name: 'AAA' } }, { pin: 'AAA111', product: { id: '200', code: 'BBB', name: 'BBB' } } ] }, { Id: 2, dealProducts: [{ pin: '', product: { id: '300', code: 'CCC', name: 'CCC' } }, { pin: '1', product: { id: '200', code: 'AAA', name: 'BBB' } }, { pin: '1', product: { id: '200', code: 'BBB', name: 'BBB' } }, { pin: '', product: { id: '400', code: 'DDD', name: 'DDD' } }, { pin: 'AAA111', product: { id: '100', code: 'AAA', name: 'AAA' } } ] } ]; const pinArray = AllPackages.flatMap(p => p.dealProducts).filter(obj => obj.product.code === 'AAA').map(data => data.pin); console.log(pinArray);
Hi you could do something like this:嗨,你可以这样做:
const PinArray3 = AllPackages.flatMap((p) => p.dealProducts).reduce(
(acc, dealProduct) => (dealProduct.product.code === "AAA" ? [...acc, dealProduct.pin] : acc),
[]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.