0

I have a scenario where I am trying to parse through this below json and get all the value of key "name" and key "id" , which I would further store in a variable or array.

  [
      {
        "metadata": {
          "id": "vvvvvvvvvvvvv",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app1",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvccc",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app2",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvddd",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app3",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvveee",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app4",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvfff",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app5",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
    }
    ]

What I have tried till now( after this not sure how to proceed as this itself provides wrong result)

 const dJSON = require('dirty-json');

 const jsn = dJSON.parse(get_all)
 console.log(JSON.stringify(jsn));
 jsonData = JSON.stringify(jsn)
 console.log(jsonData.length) //this returns wrong value

for(var i = 0; i < jsonData.length; i++){
    for(key in jsonData[i].entity){
      if(jsonData[i].entity[key] == "name"){
          return console.log(key);
          }
      }
}

This doesn't returns the expected output. Can someone advice here as I am new to nodejs & javascript on how can I extract result like this

expected o/p :

{ 
  "app1"   :  "vvvvvvvvvvvvv", 
  "app2"   :  "vvvvvvvvvvccc",
  "app3"   :  "vvvvvvvvvvddd",
  "app4"   :  "vvvvvvvvvveee",
  "app5"   :  "vvvvvvvvvvfff" 
}
2
  • will the metadata key and entity key always be the same Commented Oct 15, 2019 at 16:36
  • @Nicolas yes indeed Commented Oct 15, 2019 at 17:47

6 Answers 6

3

Here I use JSON.parse so I can use the Array.map method on the data, I use Object destructuring in the callback passed to map to pull values metadata.id and entity.name into the scope of the function. I then return a single object with entity.name as a key and metadata.id as the value. The return value from map is a new array, therefore I can use Array.reduce to transform the array into a different data structure. On each iteration of reduce the parameter current will be the individual object that was returned out of each iteration of map. Because Object.keys(current) will always be of length 1 I can use destructuring to pull the only key name out & use key/name to populate the return object.

const json = `[
    {
      "metadata": {
        "id": "vvvvvvvvvvvvv",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app1",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvccc",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app2",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvddd",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app3",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvveee",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app4",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvfff",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app5",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
  }
  ]`;

const result = JSON.parse(json)
    .map(({ metadata: { id }, entity: { name } }) => {
        return { [name]: id };
    })
    .reduce((prev, current) => {
        const [name] = Object.keys(current);

        prev[name] = current[name];

        return prev;
    }, {});

console.log(result);

Sign up to request clarification or add additional context in comments.

8 Comments

Hi, could you add a little bit more information about your answer ? Providing just code does not help.
your code returns this result { app1: undefined, app2: undefined, 'app3': undefined, app4: undefined, app5: undefined }
@Thomas are you sure, the code snippet is working fine.
@Nicolas please see explanation
@Thomas you need to update your question with the JSON that has the quotes. Double check your JSON, because its there in your data and not in your question.
|
2

welcome to stackoverflow ! You only need to loop through your Json once, and then get the metadata.id and the entity.name of each element :

let json = [
      {
        "metadata": {
          "id": "vvvvvvvvvvvvv",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app1",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvccc",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app2",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvddd",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app3",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvveee",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app4",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
      },
        {
        "metadata": {
          "id": "vvvvvvvvvvfff",
          "url": "cccccccccccccc",
          "created_at": "2019-09-06T08:40:41Z",
          "updated_at": "2019-09-06T13:25:46Z"
        },
        "entity": {
          "name": "app5",
          "b_enabled": false,
          "d_url": "xxxxxs"
        }
    }
    ]
    
  
    let output = {};
    
    // we parse each element of the json array
    for(let i = 0; i < json.length; i ++ ) {
      // we get the current element.
      let currentElement = json[i];
      // here, we are using the name of the entity as the key and the id of the metadata as the value
      output[currentElement.entity.name] = currentElement.metadata.id;
    }
    
    console.log(output);

Comments

0

You can use a simple forEach() function to iterate over your array. You can use the current iteration item to fill another object, like you've requested in your question.

So first you can create a object to store the filtered results in:

output = {}

Next, you can iterate over the array and fill your output object:

your_array.forEach(item => {output[item.entity.name] = item.metadata.id})

This will fill up the output object with the key-value pairs.

So what it exactly does, is that for each item in your_array, it will execute the (lambda) function {output[item.entity.name] = item.metadata.id}, where item is the current iteration item.


Total code:

var output = {};
your_array.forEach(item => {output[item.entity.name] = item.metadata.id});

// output will now be: 
//  { 
//    "app1"   :  "vvvvvvvvvvvvv", 
//    "app2"   :  "vvvvvvvvvvccc",
//    "app3"   :  "vvvvvvvvvvddd",
//    "app4"   :  "vvvvvvvvvveee",
//    "app5"   :  "vvvvvvvvvvfff" 
//  }

2 Comments

It gives following error Error: TypeError: jsonData.forEach is not a function
@thomas, That is because your jsonData is a string, not an array (because you used JSON.stringify earlier. Use your variable jsn instead of jsonData.
0

var arr=[
    {
      "metadata": {
        "id": "vvvvvvvvvvvvv",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app1",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvccc",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app2",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvddd",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app3",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvveee",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app4",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
    },
      {
      "metadata": {
        "id": "vvvvvvvvvvfff",
        "url": "cccccccccccccc",
        "created_at": "2019-09-06T08:40:41Z",
        "updated_at": "2019-09-06T13:25:46Z"
      },
      "entity": {
        "name": "app5",
        "b_enabled": false,
        "d_url": "xxxxxs"
      }
  }
  ]
  
  var myMap =new Map();
 
  arr.forEach((element,index)=>{
    var a= arr[index]
    var id='';
    var name='';
    
   var c= Object.keys(a).map(item=>{
     // console.log(item)
       if(item=="metadata"){
       id=a[item]["id"]
       
       }
      else{
         name=a[item]["name"]
         
         }
        }
   )
  myMap[name]=id;
      
     
  })
  console.log(myMap)
   
 

Well not the best and optimized solution (i am too new to js) but this solves your problem statement. I am just trying to get the each element of an array which is object and then within each object trying to get the keys of the individual and storing it in variable and then pushing it to the map for desired output. P.s. use you input as arr. enter image description here

5 Comments

Did you run your code snippet? It produces an error.
in visual studio it is showing the output. Let me debug it
You haven't included the JSON in the example code snippet. You might want to update your code snippet or remove it since it doesn't work.
@AyushiKeshri i am not sure but when i try this , it gives me Error: TypeError: arr.forEach is not a function
@Thomas it is working code in vsc , codepen and here .So might be you are doing something wrong.Also common mistake the input is array if you are taking it an object then object dont have for each loop in that case refer: stackoverflow.com/questions/31096596/…
-1
  const jsObj = JSON.parse(json);
  const result = jsObj.map(entry => ({name: entry.entity.name, id: entry.metadata.id}));
  const objResult = {};
  result.forEach(entry => {
    objResult[entry.name] = entry.id;
  });
  console.log(objResult);

Output:

{ app1: 'vvvvvvvvvvvvv',
  app2: 'vvvvvvvvvvccc',
  app3: 'vvvvvvvvvvddd',
  app4: 'vvvvvvvvvveee',
  app5: 'vvvvvvvvvvfff' }

1 Comment

Hi, could you add more information about your answer ?
-1

In output

key = entity.name

val = metadata.id

of each doc

The approach is simple. Intilize an empty object. Put key, val in empty object.

var result = {}
jsonData.forEach(x => {
   result[x.entity.name]= x.metadata.id
})

https://jsfiddle.net/v8w2L1oa/

3 Comments

Hi, could you add more information about your answer ?
this returns an array, the question ask for an object to be returned
@DanStarns Hey, can you check js filddle once. You will get clear answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.