简体   繁体   中英

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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