Generic solution to create an Object of unknown deepth from an Array

后端 未结 1 364
情话喂你
情话喂你 2021-01-20 06:32

I need to create a JSON object as follows:

{
    \"app_name\": \"foo\",
    \"meta\": {
        \"title\": \"foo\",
        \"lang\": \"bar\"
    },
    \"te         


        
1条回答
  •  盖世英雄少女心
    2021-01-20 06:59

    You could take an iterative approach by using a default object if a property does not exists.

    function setValue(object, key, value) {
        var path = key.split('.'),
            last = path.pop();
    
        path.reduce(function (o, k) {
            return o[k] = o[k] || {};
        }, object)[last] = value;
    }
    
    var translations = [{ key: "app_name", val: "foo" }, { key: "meta.title", val: "foo" }, { key: "meta.lang", val: "bar" }, { key: "teaser.foo.headline", val: "foo" }, { key: "teaser.foo.subline", val: "bar" }],
        object = {};
    
    translations.forEach(function (o) {
        setValue(object, o.key, o.val);
    });
    
    console.log(object);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题