第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

計(jì)算嵌套對(duì)象數(shù)

計(jì)算嵌套對(duì)象數(shù)

鴻蒙傳說(shuō) 2023-02-24 16:46:17
const json = [{  "order": 1111,  "items": [    {      "colour1": "red",      "colour2": "yellow",    },    {      "colour1": "red",      "colour2": "red",    },    {      "colour1": "red",      "colour2": "red",    }  ]},{  "order": 2222,  "items": [    {      "colour1": "black",      "colour2": "blue",      "colour3": "orange"    },    {      "colour1": "white",      "colour2": "red",      "colour3": "green",          }  ]}]Object.entries(json).forEach(([i, v]) => {    let count = [];    Object.entries(v.items).forEach(([j, k]) => {        if (k.colour2.includes('red')) {            count.push(k.colour2)        }    });    console.log(count, count.length) //length = [2, 1]});我覺得我寫的這段代碼不是過(guò)濾和計(jì)算長(zhǎng)度的有效方法。目標(biāo)是過(guò)濾某個(gè)值并得到結(jié)果。尋找替代方法和正確的 es6 方法來(lái)做到這一點(diǎn)。謝謝
查看完整描述

3 回答

?
幕布斯6054654

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊

使用reduce()

const json = [{"order":1111,"items":[{"colour1":"red","colour2":"yellow"},{"colour1":"red","colour2":"red"},{"colour1":"red","colour2":"red"}]},{"order":2222,"items":[{"colour1":"black","colour2":"blue","colour3":"orange"},{"colour1":"white","colour2":"red","colour3":"green"}]}]


const res = json.reduce((acc, order) => {

  let red = order.items.filter(color => color.colour2 === 'red')

  return red.length ? [...acc, red.length] : acc

}, [])


console.log(res)

注意:要獲得過(guò)濾后的結(jié)果而不是計(jì)數(shù)返回[...acc, red]



查看完整回答
反對(duì) 回復(fù) 2023-02-24
?
瀟湘沐

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊

將有多種方法解決此問題,但如果您只對(duì)出現(xiàn)“colour2”:“red”感興趣。您也可以使用類似的東西。


 let json = [{"order":1111,"items":[{"colour1":"red","colour2":"yellow"},{"colour1":"red","colour2":"red"},{"colour1":"red","colour2":"red"}]},{"order":2222,"items":[{"colour1":"black","colour2":"blue","colour3":"orange"},{"colour1":"white","colour2":"red","colour3":"green"}]}]

   let count=[];

    for(let i of json){

    count.push(JSON.stringify(i).match(/"colour2":"red"/g).length)

    }

console.log(count);


查看完整回答
反對(duì) 回復(fù) 2023-02-24
?
烙印99

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊

也許這里的效率不是最好的,但它是可以理解的代碼:


let count = [];

json.forEach((order, index) => {

  count[index] = [];

  order.items.forEach((item) => {

    if (item.colour2 === "red") {

      count[index].push(item.colour2);

    }

  });

});

console.log(count);


查看完整回答
反對(duì) 回復(fù) 2023-02-24
  • 3 回答
  • 0 關(guān)注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)