如何迭代对象并构建一个新对象

时间:2015-06-16 12:32:25

标签: javascript object nested

我使用JavaScript在一个对象中迭代客户,该对象构造如下:

[
{
    "customer": "Customer 1",
    "project": "1"
},
{
    "customer": "Customer 2",
    "project": "2"
},
{
    "customer": "Customer 2",
    "project": "3"
}
]

我希望在迭代中构建一个新对象,其构造方式如下:

[
{
    "Customer 1": {
        "projects": "1"
    }
},
{
    "Customer 2": {
        "projects": [
            "2",
            "3"
        ]
    }
}
]

有关如何实现这一目标的任何提示?

2 个答案:

答案 0 :(得分:0)

您可以创建一个中间对象来形成内部对象。使用该对象上的迭代器从中形成数组。

请参阅下面的示例代码。

var response = [
{
    "customer": "Customer 1",
    "project": "1"
},
{
    "customer": "Customer 2",
    "project": "2"
},
{
    "customer": "Customer 2",
    "project": "3"
}
];

var length = response.length,
    i = 0,
    result = {},
    j = 0,
    finalResult = [];

for(;i<length;i++){
    var eachObj = response[i];
    if(!result[response[i].customer]){
       result[response[i].customer] = [response[i].project];
    }
    else{
        result[response[i].customer].push(response[i].project);
    }
}

for(var key in result){  
    var eachObj = [];
    eachObj[key] = result[key];
    finalResult.push(eachObj);
}

console.log(finalResult);

答案 1 :(得分:-1)

在新数组中查找客户,如果找到添加项目,否则添加客户。

var data = [
    {
        "customer": "Customer 1",
        "project": "1"
    },
    {
        "customer": "Customer 2",
        "project": "2"
    },
    {
        "customer": "Customer 2",
        "project": "3"
    }
];
var newData = [];
data.forEach(function (el, i) {
    var customer = newData.filter(function (ell) {
        return el.customer === ell.customer;
    })[0];
    if (customer) {
        customer.projects.push(el.project);
    } else {
        newData.push({ customer: el.customer, projects: [el.project] });
    }
});
document.write('<pre>' + JSON.stringify(newData, null, 4) + '</pre>');