猿问

简化嵌套对象并查找特定属性的总和

我有一个嵌套的对象,如下所示。我想将嵌套对象简化为一个对象,并查找特定父对象的所有子级的特定属性的总和。


当前对象


let obj = {

Myanmar: [

    {

        trk1: {

            mou: 0.0,

            ca: 1.0,

            ccs: 0.0,

            ccc: 0.0,

        },

    }

],

Gibraltar: [

    {

        trk1: {

            mou: 12.850000381469727,

            ca: 1.0,

            ccs: 1.0,

            ccc: 3.0,

        },

    }

],

Cyprus: [

    {

        trk1: {

            mou: 36.25,

            ca: 3.0,

            ccs: 2.0,

            ccc: 7.0,

        },

        trk2: {

            mou: 27.299999237060547,

            ca: 1.0,

            ccs: 1.0,

            ccc: 6.0,

        },

        trk3: {

            mou: 80.59999752044678,

            ca: 4.0,

            ccs: 4.0,

            ccc: 14.0,

        },

        trk4: {

            mou: 26.716670513153076,

            ca: 4.0,

            ccs: 4.0,

            ccc: 6.0,

        }

    }

]};

预期对象


{

Myanmar: {

    mou: "(trk1-mou+trk2-mou+trk3-mou)",

    ca: "(trk1-ca+trk2-ca+trk3-ca)"

}};

我想对嵌套对象执行属性的总和。我无法继续后得到对象.键请帮助.


慕容森
浏览 88回答 2
2回答

白猪掌柜的

我不确定这是否是你想要的:var obj={"Myanmar": [{ "trk1": { "mou": 0.0, "ca": 1.0, "ccs": 0.0, "ccc": 0.0 }}],"Gibraltar": [{ "trk1": { "mou": 12.850000381469727, "ca": 1.0, "ccs": 1.0, "ccc": 3.0 }}],"Cyprus": [{ "trk1": { "mou": 36.25, "ca": 3.0, "ccs": 2.0, "ccc": 7.0 }, "trk2": { "mou": 27.299999237060547, "ca": 1.0, "ccs": 1.0, "ccc": 6.0 }, "trk3": { "mou": 80.59999752044678, "ca": 4.0, "ccs": 4.0, "ccc": 14.0 }, "trk4": { "mou": 26.716670513153076, "ca": 4.0, "ccs": 4.0, "ccc": 6.0 }}]}result = Object.entries(obj).reduce((acc, [k,v])=>{ acc[k] = acc[k] || {}; Object.entries(v[0]).forEach(([_, country])=>{ for(let [key, value] of Object.entries(country)){     acc[k][key] = acc[k][key] || 0;     acc[k][key] += value;   } }) return acc;},{});console.log(result);

长风秋雁

var obj={"Myanmar": [{ "trk1": { "mou": 0.0, "ca": 1.0, "ccs": 0.0, "ccc": 0.0 }}],"Gibraltar": [{ "trk1": { "mou": 12.850000381469727, "ca": 1.0, "ccs": 1.0, "ccc": 3.0 }}],"Cyprus": [{ "trk1": { "mou": 36.25, "ca": 3.0, "ccs": 2.0, "ccc": 7.0 }, "trk2": { "mou": 27.299999237060547, "ca": 1.0, "ccs": 1.0, "ccc": 6.0 }, "trk3": { "mou": 80.59999752044678, "ca": 4.0, "ccs": 4.0, "ccc": 14.0 }, "trk4": { "mou": 26.716670513153076, "ca": 4.0, "ccs": 4.0, "ccc": 6.0 }}]}let reqObj={};let arr = Object.keys(obj);for(var i=0;i<=arr.length-1;i++){&nbsp;let inObj = obj[arr[i]][0];&nbsp;reqObj[arr[i]] = Object.keys(inObj).reduce((acc,ele,index)=>{&nbsp; &nbsp; &nbsp;let keyArr = Object.keys(inObj[ele]);&nbsp; &nbsp; &nbsp;for(var j=0;j<=keyArr.length-1;j++){&nbsp; &nbsp; &nbsp; &nbsp;acc = {...acc,...{[keyArr[j]] : (keyArr[j] in acc)&nbsp; &nbsp;? acc[keyArr[j]] + inObj[ele][keyArr[j]]&nbsp; &nbsp;: inObj[ele][keyArr[j]]}}&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return acc;&nbsp; },{})}&nbsp; console.log(reqObj)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答