简体   繁体   English

基本编程 - 多维对象的对象数组

[英]Basic programming - array of objects to a multi-dimensional object

I've been stuck on this for hours. 我已经坚持了几个小时。

I have a list of objects: 我有一个对象列表:

const myCompanyList = [
    {name: 'coca-cola', size: 'big', color: 'red'},
    {name: 'my-cola', size: 'small', color: 'purple'},
    {name: 'pepsi', size: 'big', color: 'blue'}
];

I need to get it into this format: 我需要把它变成这种格式:

myJson = {
    companies: {
        big: {
            coca-cola: {color: 'red'},
            pepsi: {color: 'blue'}
        },
        small: {
            my-cola: {color: 'purple'}
        }
    }
}

I've tried doing this: 我试过这样做:

wrapperObject = {};
innerObject = {};

for each object in myCompanyList {
    innerObject[object.size] = { object.name : {color: object.color}}

}

but the object[name] bit overwrites. 但是对象[name]位会被覆盖。 How can I write this so I can dynamically get names on each object/map level? 我怎么写这个,这样我就能在每个对象/地图级别动态获取名字? Do I need to make another inner object/map to dynamically write the names? 我是否需要制作另一个内部对象/地图来动态写入名称?

I've tried writing this in Java but I ended up with 5 dimensional maps and it didn't work, so I just wondered if there was something simple I'm missing - answers in Java, javascript or pseudocode thanks. 我已经尝试用Java写这个,但我最终得到了5维地图并且它没有用,所以我只是想知道是否有一些简单的我缺少 - 用Java,javascript或伪代码回答谢谢。

You can use Array.reduce() to create a map, Try the following : 您可以使用Array.reduce()创建地图,请尝试以下操作:

 let myCompanyList = [{name: "coca-cola", size: "big", color: "red"}, {name: "my-cola", size: "small", color: "purple"},{name: "pepsi", size: "big", color:"blue"}]; let result = {}; result.companies = myCompanyList.reduce((a,curr)=>{ a[curr.size] = a[curr.size] || {}; a[curr.size][curr.name] = {"color" : curr.color}; return a; },{}); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM