我想获取嵌套键并处理其数据。
我尝试了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中,我同时获得了键
name
和data
。在示例2中,我仅得到a,b,c,d,是,否,f,hgs,cft,vit。不 他们的价值观。
但是我想:
仅获取数据。
并像
{"key":"a","value":"some text"},{"key":"b","value":"some text"},{"key":"c","value":"c for"},{},{}
那样操作它们的值。
这是我的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"
}
}
}
答案 0 :(得分:0)
您可以使用 Object.values
提取内部data
对象,并提取key
对象的每个value
和data
可以通过 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);