Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 get key and value from json array with dynamic key

I want to get key and value from json array with dynamic keys. Meaning, I don't know in advance what will be the keys.

This is an example to the json the function gets:

arr = [
       {key1: 'val1'},
       {key2: 'val2'},
       {key3: 'val3'}
      ];

It seems simple to me but I am unable to get the key and value for each item.

This is what I tried (based on this pipe):

for (let key of arr) {
   console.log ('key: ' +  key + ',  value: ' + arr[key]);
 }

But what I get in the log is the following:

key:[object Object], value: undefined

My expected behavior is to get the following:

key:key1, value:val1

What am I doing wrong? How can I get the keys and values?

like image 258
Batsheva Avatar asked Jul 30 '17 10:07

Batsheva


2 Answers

In your example, you have an array of objects and each of these object has exactly one property.

for (let obj of arr) {
    console.log("object:", obj);
    for (let key in obj) {
        console.log("      key:", key, "value:", obj[key]);
    }
}

The following code from your posting

for (let key in arr) {
    console.log ('key: ' +  key + ',  value: ' + arr[key]);
}

... would work on a data structure like this:

let arr = {
    key1: 'val1',
    key2: 'val2',
    key3: 'val3'
};
like image 197
Hendrik Brummermann Avatar answered Sep 30 '22 01:09

Hendrik Brummermann


If you are more concerned to specify object like

var temp={'name':Dinesh,'age':18}

You may use following syntax.

console.log(Object.keys(temp)[0],Object.values(temp)[0]):

Specially zero index because object's both method keys and values return an array

like image 24
Sachin Mishra Avatar answered Sep 30 '22 02:09

Sachin Mishra