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" 
}
Thomas
  • 99
  • 2
  • 12

6 Answers6

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);
Dan Starns
  • 3,765
  • 1
  • 10
  • 28
  • Hi, could you add a little bit more information about your answer ? Providing just code does not help. – Nicolas Oct 15 '19 at 16:41
  • your code returns this result `{ app1: undefined, app2: undefined, 'app3': undefined, app4: undefined, app5: undefined }` – Thomas Oct 15 '19 at 16:54
  • @Thomas are you sure, the code snippet is working fine. – Dan Starns Oct 15 '19 at 16:57
  • @Nicolas please see explanation – Dan Starns Oct 15 '19 at 16:57
  • @DanStarns Yup , I just checked it returns but like this `{ app1 : 'vvvvvvvvvvvvv', app2 : 'vvvvvvvvvvccc', 'app3' : 'vvvvvvvvvvddd', app4 : 'vvvvvvvvvveee', app5 : 'vvvvvvvvvvfff }` however you can notice that for `app3` it returns with quotes ('app3') but others it doesnt .. why ? – Thomas Oct 15 '19 at 17:01
  • @Thomas have you executed the code snippet attached to the answer? – Dan Starns Oct 15 '19 at 17:03
  • @Thomas I cant understand your comment, it doesn't matter if an object key is surrounded in quotes this is valid javascript. You can clearly see there is no code specifying that `app3` should be surrounded by quotes. – Dan Starns Oct 15 '19 at 17:31
  • 1
    @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. – AussieJoe Oct 15 '19 at 19:36
1

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);
Nicolas
  • 8,077
  • 4
  • 21
  • 51
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" 
//  }
sampie777
  • 134
  • 6
  • It gives following error `Error: TypeError: jsonData.forEach is not a function` – Thomas Oct 15 '19 at 17:34
  • @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`. – sampie777 Oct 15 '19 at 20:12
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

Ayushi Keshri
  • 680
  • 7
  • 18
  • 1
    Did you run your code snippet? It produces an error. – AussieJoe Oct 15 '19 at 17:04
  • in visual studio it is showing the output. Let me debug it – Ayushi Keshri Oct 15 '19 at 17:11
  • 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. – AussieJoe Oct 15 '19 at 17:15
  • @AyushiKeshri i am not sure but when i try this , it gives me `Error: TypeError: arr.forEach is not a function` – Thomas Oct 15 '19 at 17:43
  • @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: https://stackoverflow.com/questions/31096596/why-is-foreach-not-a-function-for-this-object/31096661 – Ayushi Keshri Oct 15 '19 at 18:03
-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/

Srinivas
  • 294
  • 3
  • 18
-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' }
gabriel.hayes
  • 2,267
  • 12
  • 15