【问题标题】:Build Nested Object in Javascript [duplicate]用Javascript构建嵌套对象[重复]
【发布时间】:2017-11-17 14:36:56
【问题描述】:

我试图构建一个嵌套对象,我会尽量让自己清楚。

我有这个 json 结构:

 {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"  
}

我需要一个输出如下内容的函数:

{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }

我知道我必须使用递归来实现这一点,但我无法编写代码。 你们能帮我解决这个问题吗?

谢谢。

【问题讨论】:

  • @BenBeck 当您想将问题标记为重复时,只需使用关闭链接,它会为您添加评论:)

标签: javascript json object


【解决方案1】:

各位,

@Ben Beck 的回答帮助了我。

我只需要对函数做一些小改动:

function (path,value,obj) {

    var parts = path.split("."), part;

    //reference the parent object
    var parent = obj;

    while(part = parts.shift()) {

        // here I check if the property already exists
        if( !obj.hasOwnProperty(part) ) obj[part] = {};

        // if is the last index i set the prop value
        if(parts.length === 0) obj[part] = value;

        obj = obj[part]; // update "pointer"
    }

    //finally return the populated object
    return parent;

}

【讨论】:

    【解决方案2】:

    您可以使用例如达到所需的解决方案Array#reduce.

    const o = {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan",
    };
    
    const r = Object.keys(o).reduce((s, a) => {
      const t = a.split('.');
      const k = t[0];
      const v = t[t.length - 1];
      k in s ? s[k][v] = o[a] : s[k] = Object.assign({}, { [v]: o[a] });
      return s;
    }, {});
    
    console.log(r);

    【讨论】:

    • 这已经被回答了。您应该将其标记为已关闭。
    • @Archer 答案在哪里?
    • 查看问题下的 2 个“可能重复..”链接
    • @Archer 好吧,这只是解决该问题的另一种方法。显示完全相同的解决方案,我将立即删除我的答案。
    猜你喜欢
    • 2018-02-27
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2019-08-28
    • 2018-04-26
    相关资源
    最近更新 更多