如何获取json数组中的多个键的键并操纵它们的数据?

时间:2019-03-15 10:30:29

标签: javascript arrays json object key

我想获取嵌套键并处理其数据。
我尝试了2种方法:

Example 1: 
    for (let key in the dictionary) {
        for (let keys in dictionary[key]) {
            console.log(keys) 
        }
    }
Example 2:
 for (let key in dictionary) {
     for (let k in lng.dictionary[key]["data"]) {
         console.log(k)
     }
 }
  

在示例1中,我同时获得了键namedata

     

在示例2中,我仅得到a,b,c,d,是,否,f,hgs,cft,vit。不   他们的价值观。

但是我想:

  
      
  1. 仅获取数据。

  2.   
  3. 并像{"key":"a","value":"some text"},{"key":"b","value":"some text"},{"key":"c","value":"c for"},{},{}那样操作它们的值。

  4.   

这是我的Json对象

"dictionary" : {
                    "bar" : {
                            "name" : "Bar",
                            "data" : {
                                    "a" : "some text",
                                    "b" : "some text",
                                    "c" : "c for",
                                    "d" : "some text",
                                    "yes" : "true",
                                    "No" : "true",
                                    "f" : "some text"
                            }
                    },
                    "text" : {
                            "name" : "Text",
                            "data" : {
                                    "hgs" : "some text",
                                    "cft" : "some text",
                                    "vit" : "some text"
                            }
                    }
            }

1 个答案:

答案 0 :(得分:0)

您可以使用 Object.values 提取内部data对象,并提取key对象的每个valuedata可以通过 Object.entries 进行迭代,我们将形成一个temp对象。

使用 Array.reduce ,我们可以将temp个对象累积到一个数组中。

const data = {"dictionary":{"bar":{"name":"Bar","data":{"a":"some text","b":"some text","c":"c for","d":"some text","yes":"true","No":"true","f":"some text"}},"text":{"name":"Text","data":{"hgs":"some text","cft":"some text","vit":"some text"}}}};

const dataProcessed = Object.values(data.dictionary).reduce((acc, obj) => {
  Object.entries(obj.data).forEach(([key, value])=>{
    temp = {};
    temp["key"] = key;
    temp["value"] = value;
    acc.push(temp);
  });
return acc;
}, []);
console.log(dataProcessed);