0

I want to fetch the nested key and manipulates their data.
I have tried 2 methods:

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

In Example 1, I am getting both the keys name and data.

In Example 2,I am getting only a, b, c, d, yes, no, f, hgs, cft, vit. not their values.

But I want to:

  1. Fetch only data.

  2. and manipulate their values like {"key":"a","value":"some text"},{"key":"b","value":"some text"},{"key":"c","value":"c for"},{},{}.

here is my Json object

"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"
                            }
                    }
            }
Schüler
  • 512
  • 4
  • 10
  • 25

1 Answers1

1

You can use Object.values to extract the inner data object and for each key and value of the data object which can be iterated by Object.entries we would form a temp object.

Using Array.reduce we can accumulate the temp objects into an array.

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);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44