亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對嵌套對象數組進行分組

對嵌套對象數組進行分組

慕容森 2022-08-18 09:47:35
我有以下對象:const attributes = [    {        id: "a",        values: [            {                value: [                    {                        _id: "aa",                        value: "1500"                    },                    {                        _id: "ab",                        value: "580"                    }                ]            },            {                value: [                    {                        _id: "aa",                        value: "400"                    }                ]            }        ]    },    {        id: "a",        values: [            {                value: [                    {                        _id: "aa",                        value: "420"                    },                    {                        _id: "ab",                        value: "300"                    }                ]            },            {                value: [                    {                        _id: "aa",                        value: "480"                    },                    {                        _id: "ab",                        value: "1000"                    }                ]            },            {                value: [                    {                        _id: "aa",                        value: "880"                    },                    {                        _id: "ab",                        value: "740"                    }                ]            }        ]    },    {        id: "b",        values: [            {                value: [                    {                        _id: "ba",                        value: "1500"                    },                    {                        _id: "bb",                        value: "580"                    }                ]如果結果沒有意義,我可以解釋更多。無論如何,我試圖通過執行以下操作來嘗試結果,但它沒有按預期工作,我相信有一種更干凈的方法可以做到這一點。
查看完整描述

3 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

const attributes = [

    {

        id: "a",

        values: [

            {

                value: [

                    {

                        _id: "aa",

                        value: "1500"

                    },

                    {

                        _id: "ab",

                        value: "580"

                    }

                ]

            },

            {

                value: [

                    {

                        _id: "aa",

                        value: "400"

                    }

                ]

            }

        ]

    },

    {

        id: "a",

        values: [

            {

                value: [

                    {

                        _id: "aa",

                        value: "420"

                    },

                    {

                        _id: "ab",

                        value: "300"

                    }

                ]

            },

            {

                value: [

                    {

                        _id: "aa",

                        value: "480"

                    },

                    {

                        _id: "ab",

                        value: "1000"

                    }

                ]

            },

            {

                value: [

                    {

                        _id: "aa",

                        value: "880"

                    },

                    {

                        _id: "ab",

                        value: "740"

                    }

                ]

            }

        ]

    },

    {

        id: "b",

        values: [

            {

                value: [

                    {

                        _id: "ba",

                        value: "1500"

                    },

                    {

                        _id: "bb",

                        value: "580"

                    }

                ]

            },

            {

                value: [

                    {

                        _id: "ba",

                        value: "400"

                    }

                ]

            }

        ]

    },

];


let newStructure = 

    attributes.map(attr => {

        let tempValues = {};

        attr.values.forEach((value, index)=> { 

            value.value.forEach((v)=>{

                if(typeof tempValues[v._id] == "undefined")

                    tempValues[v._id] = 0;

                tempValues[v._id] += +v.value


            })

        })

        return {

            id: attr.id,

            values: tempValues

        }


}).reduce((accumulator, currentValue)=>{

    if(typeof accumulator[currentValue.id] == "undefined")

        accumulator[currentValue.id] = { id: currentValue.id, values: {} };

    Object.keys(currentValue.values).forEach( valueKey =>{

        if(typeof accumulator[currentValue.id].values[valueKey] == "undefined")

                accumulator[currentValue.id].values[valueKey] = [currentValue.values[valueKey]];

        else

                accumulator[currentValue.id].values[valueKey].push(currentValue.values[valueKey]);

    })

    

    return accumulator

},{})


newStructure = Object.keys(newStructure).map(itemKey => {

    return {

        id: itemKey,

        values: {

            value: Object.keys(newStructure[itemKey].values).map(valueKey => {

                return  {

                    _id: valueKey,

                    value: newStructure[itemKey].values[valueKey]

                }

            })

        }

    }

});


console.log(newStructure)


查看完整回答
反對 回復 2022-08-18
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

使用更直接/原生的javascript對象形式,我能夠使大多數部分更加離散。此代碼通常假定對象可能沒有給定索引的初始值,因此不會根據您似乎具有的初始化和將來假設僅使用這些索引的初始值執行任何優化。attribute.values[0]


let newAttributes = {}; // will be converted back

for (attribute of attributes){


    let newValues = []; // turn it into [ { "aa":1500, "ab":580 }, {"aa":400} ]

    for (valueSet of attribute.values){

        let newObj = {};

        for (value of valueSet.value){

            newObj[value._id] = Number(value.value);

        }

        newValues.push(newObj);

    }


    let sum = {};

    for (value of newValues){

        for (id in value){

            if (!(id in sum)) sum[id] = 0;

            sum[id] += value[id];

        }

    }


    if ( !(attribute.id in newAttributes))

        newAttributes[attribute.id] = {};


    outAttrib = newAttributes[attribute.id]

    for (id in sum){

        if ( !(id in outAttrib)) outAttrib[id] = [];

        outAttrib[id].push(sum[id].toString());

    }


}

// at this point, the object would be in, imo, more manageable form

// a: { aa: [ '1900', '1780' ], ab: [ '580', '2040' ] },

// b: { ba: [ '1900' ], bb: [ '580' ] }


let out = [];

for (id in newAttributes){ // can be integrated into former loop but I think this makes more sense

    let value = [];

    for (_id in newAttributes[id]){

        value.push({_id: _id, values: newAttributes[id][_id]});

    }

    out.push({id: id, values: [ { value: value } ] });

}

console.log(out);


查看完整回答
反對 回復 2022-08-18
?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

我從頭開始編寫代碼,它正在工作


const attributes = [

  {

      id: "a",

      values: [

          {

              value: [

                  {

                      _id: "aa",

                      value: "1500"

                  },

                  {

                      _id: "ab",

                      value: "580"

                  }

              ]

          },

          {

              value: [

                  {

                      _id: "aa",

                      value: "400"

                  }

              ]

          }

      ]

  },

  {

      id: "a",

      values: [

          {

              value: [

                  {

                      _id: "aa",

                      value: "420"

                  },

                  {

                      _id: "ab",

                      value: "300"

                  }

              ]

          },

          {

              value: [

                  {

                      _id: "aa",

                      value: "480"

                  },

                  {

                      _id: "ab",

                      value: "1000"

                  }

              ]

          },

          {

              value: [

                  {

                      _id: "aa",

                      value: "880"

                  },

                  {

                      _id: "ab",

                      value: "740"

                  }

              ]

          }

      ]

  },

  {

      id: "b",

      values: [

          {

              value: [

                  {

                      _id: "ba",

                      value: "1500"

                  },

                  {

                      _id: "bb",

                      value: "580"

                  }

              ]

          },

          {

              value: [

                  {

                      _id: "ba",

                      value: "400"

                  }

              ]

          }

      ]

  },

];


newAttributes = [];

attributes.forEach(attribute => {

  childOutput = childNode(attribute.values)


  var isIdPresent = newAttributes.filter(e => {

    return  e.id == attribute.id

  });


  if (isIdPresent.length > 0) {

    var parentNode = isIdPresent[0]

    newAttributes = newAttributes.filter(e => {

      return  e.id != attribute.id

    });

    parentNode["values"][0].value = (mergeChildNode(parentNode["values"][0].value, childOutput))

    newAttributes.push(parentNode)

  } else {

    var parentNode ={}

    parentNode["id"] = attribute.id

    parentNode["values"] = [{value:[]}]

    parentNode["values"][0].value = (mergeChildNode(parentNode["values"][0].value, childOutput))

    newAttributes.push(parentNode)

  }

});


console.log(JSON.stringify(newAttributes));



function childNode(attrValues){

  childOutput = {}

  attrValues.forEach(valueArray => {

    valueArray.value.forEach(valueObj => {

      if (childOutput.hasOwnProperty(valueObj._id)) {

        childOutput[valueObj._id] = childOutput[valueObj._id] + parseInt(valueObj.value)

      } else {

        childOutput[valueObj._id] = parseInt(valueObj.value)

      }

    });

  });

  return childOutput

}


function mergeChildNode (inputArray, childOutput) {

  for (const property in childOutput) {

    var isIdPresent = inputArray.filter(e => {

      return  e._id == property

    });


    if (isIdPresent.length > 0) {

      var newObj = isIdPresent[0];

      inputArray = inputArray.filter(e => {

        return  e._id != property

      });

      newObj["values"].push(childOutput[property])

      inputArray.push(newObj)

    } else {

      inputArray.push({

        _id: property,

        values: [childOutput[property]]

      })

    }

  }

  return inputArray


查看完整回答
反對 回復 2022-08-18
  • 3 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號