简体   繁体   English

在javascript中提取字段

[英]extract fields in javascript

I have a dictionary where i want to extract some fields with their keys.我有一本字典,我想用它们的键提取一些字段。 So what i want is call a function where i pass this dictionary and the keys.所以我想要的是调用一个函数,在那里我传递这本字典和键。

var posts = {
     "code":"ok",
     "data":[
            {
              "id":1, 
              "username":"example1",
              "data":
                      {
                        "id":4,
                        "name":"fran"
                      },
            },
            {
              "id":2, 
              "username":"example2",
               "data":
                  {
                    "id":5,
                    "name":"manuel"
                  }            
           }
           ]
    };

So I would like to have a new dictionary where i have the nested value as a simple dictionary value.所以我想要一个新的字典,我将嵌套值作为一个简单的字典值。

          [{
          "id":1, 
          "username":"example1",
          "name":"fran"
          },

          "id":2, 
          "username":"example2",
          "name":"manuel"
          }}            
function dict(obj)
{
    var list = Object.assign({},obj).data;

    list.forEach((e,i,a) => {
        e.name = e.data.name;
        delete e.data;
    });

    return list;
}

that's how you dictionary function should look这就是你的字典函数应该看起来的样子

I have tried this one.我试过这个。 I think i have problem because i am creating a dictionary when node is "name" in the iteration.我想我有问题,因为当节点在迭代中是“名称”时,我正在创建一个字典。 So i want to confirm if it's OK or there is any another way to do this.所以我想确认是否可以,或者是否有其他方法可以做到这一点。

var list = [];      
    var dict = {};
    function iterate(obj, stack) {
        for (var property in obj) {         
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {                    
                    iterate(obj[property], stack + '.' + property);                    
                } else {
                    console.log(property + "   " + obj[property]);          
                    dict[property] = obj[property];
                    if(property=="name"){
                        list.push(dict);
                        dict ={};
                    }
                }
            }           
        }

        return list;
    }

    var simplified = iterate(posts.data, '');
    console.log(simplified);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM