用JavaScript在字符串数组之外创建分组对象

时间:2018-11-16 13:53:58

标签: javascript

我有一个无法解决的问题,基本上我想解决这个问题:

{
    "seamark:name": "Z-2",
    "seamark:type": "buoy_lateral",
    "seamark:light:range": "5",
    "seamark:light:colour": "red",
    "seamark:light:character": "Q",
    "seamark:radar_reflector": "yes",
    "seamark:buoy_lateral:shape": "can",
    "seamark:buoy_lateral:colour": "red",
    "seamark:buoy_lateral:system": "iala-a",
    "seamark:buoy_lateral:category": "port"
}

对此:

{
    seamark: {
        name: "Z-2",
        type: "buoy_lateral",
        light: {
            range: "5",
            colour: "red",
            reflector: "yes"
        },
        buoy_lateral: {
            shape: "can",
            colour: "red",
            system: "iala-a",
            category: "port
        }
    }
}

到目前为止,我仅使用以下链接中显示的代码获得了一个包含10个对象的数组,每次都有指向值的路径(例如{seamark:{name:“ Z-2”}}}) : codepen

一旦我在代码笔中显示了结果,会有人对如何对属性进行深度分组有想法吗?或什至另一个想法?预先感谢

3 个答案:

答案 0 :(得分:2)

您正在尝试unflat一个对象。

您可以使用flat npm(https://www.npmjs.com/package/flat

const { unflatten } = require('flat');

const unflat = unflatten({
    "seamark:name": "Z-2",
    "seamark:type": "buoy_lateral",
    "seamark:light:range": "5",
    "seamark:light:colour": "red",
    "seamark:light:character": "Q",
    "seamark:radar_reflector": "yes",
    "seamark:buoy_lateral:shape": "can",
    "seamark:buoy_lateral:colour": "red",
    "seamark:buoy_lateral:system": "iala-a",
    "seamark:buoy_lateral:category": "port"
}, { delimiter: ":" }); // notice delimiter : default is "."

console.log(unflat);

输出:

{
    seamark: {
        name: 'Z-2',
        type: 'buoy_lateral',
        light: { range: '5', colour: 'red', character: 'Q' },
        radar_reflector: 'yes',
        buoy_lateral:
        {
            shape: 'can',
            colour: 'red',
            system: 'iala-a',
            category: 'port'
        }
    }
}

答案 1 :(得分:2)

要设置值,可以通过移动给定的对象来分割路径并缩小路径。如果不存在任何对象,请使用名称创建一个新属性。稍后分配值。

function setValue(object, path, value) {
    var last = path.pop();

    path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var data = { "seamark:name": "Z-2", "seamark:type": "buoy_lateral", "seamark:light:range": "5", "seamark:light:colour": "red", "seamark:light:character": "Q", "seamark:radar_reflector": "yes", "seamark:buoy_lateral:shape": "can", "seamark:buoy_lateral:colour": "red", "seamark:buoy_lateral:system": "iala-a", "seamark:buoy_lateral:category": "port" };

Object
    .keys(data)
    .forEach(k => {
        var keys = k.split(':');
        if (keys.length === 1) return;
        setValue(data, k.split(':'), data[k]);
        delete data[k];
    });

console.log(data);

答案 2 :(得分:0)

您还可以像下面一样使用“ for..of”和“ Array.reduce”

pip --version