[英]How can I extract specific property as an array from nested array object in JavaScript
[英]How can I extract pin property from an object and make an array of pins in JavaScript?
我已經用數組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 -->
您可以使用flatMap
簡潔地獲取所有dealProducts
的單個數組。 然后.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);
嗨,你可以這樣做:
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.