正确将JSON重组为JS数组

时间:2018-09-30 19:14:30

标签: javascript arrays multidimensional-array

我有一个类似于以下内容的JSON字符串:

[
    {"id":"112233","region":"UK","city":"London","name":"Company 1"},
    {"id":"112244","region":"UK","city":"London","name":"Company 2"},
    {"id":"112255","region":"UK","city":"Manchester","name":"Company 3"},
    {"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}
]

我正在尝试将其重建为这样的JS数组:

[
    { 
        ["London"]: [
                    ["112233"] : [{"id":"112233","region":"UK","city":"London","name":"Company 1"}],
                    ["11224"] : [{"id":"112244","region":"UK","city":"London","name":"Company 2"}],
                ],
        ["Manchester"]: [
                    ["112255"] : [{"id":"112255","region":"UK","city":"Manchester","name":"Company 3"}],
                    ["112266"] : [{"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}]
                ]
    }
]

这是我用来执行此操作的代码:

var company = [];
var companies = [];
var cities = [];

// generate citites
for (var i = 0; i < dump.length; i++)
{
    // check if city exits
    if(!cities.includes(dump[i].city.trim())) {
        cities[dump[i].city.trim()] = companies;
    }
}

// add companies
for (var i = 0; i < dump.length; i++)
{
    company['company_name'] = dump[i].company_name;
    company['region'] = dump[i].region;
    cities[dump[i].city][dump[i].id] = company;
}
console.log(cities);

现在我收到一个错误,指出Cannot set property '112233' of undefined TypeError: Cannot set property '112233' of undefined

有人可以解释我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

所需结果的格式有些奇怪,因为您正在使用[]来查找带有键的对象。我假设这是一个错别字,而您确实想要一个对象。

这是使用reduce()进行操作的快速简便方法:

let dump = [
    {"id":"112233","region":"UK","city":"London","name":"Company 1"},
    {"id":"112244","region":"UK","city":"London","name":"Company 2"},
    {"id":"112255","region":"UK","city":"Manchester","name":"Company 3"},
    {"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}
]

let obj = dump.reduce((obj, item) => {
    let city = obj[item.city] || (obj[item.city] = {}) // add city obj to object if not there.
    city[item.id] = item                               // add item.id to city obj
    return obj
}, {})
console.log(obj)

编辑:

reduce()的工作方式是从在第二个参数中传递的值开始,这里是一个空对象{},在回调中称为obj,然后进行迭代通过数组(dump)。每次迭代时,我们都会查看obj是否具有一个属性,该属性具有该迭代中当前项的名称。如果未添加,则分配一个新对象{}。然后使用该对象,添加与item.id相对应的属性,并向其添加整个item

您可以将整个内容编写为for循环,但是reduce十分简洁-只需花一点时间就可以习惯。