1

I am trying to extract some data from an array of dict but it does not work...

Here is my code :

var myarray = [{'country': 'US', 'type': 'eat'}, {'country': 'DE', 'type': 'test'}]

var arr = []
for (var key in myarray){
if (key.hasOwnProperty('country')){
        arr.push(key.country)
    }
}
console.log(arr);

What I want at the end is this arr = ['US', 'DE']

I precise I am using React.js maybe there is a function more efficient to do that ... but I did not found...

Here is my code : http://jsfiddle.net/n3o61bcw/

Thank you a lot for your help !

3 Answers 3

2
var myarray = [{'country': 'US', 'type': 'eat'}, {'country': 'DE', 'type': 'test'}];
const arr = myarray.map(c => c.country);
Sign up to request clarification or add additional context in comments.

Comments

2

The reason your code doesn't work is that the iterable key of an array is just its index. So you're checking whether 0.hasOwnProperty('country') e.t.c. which obviously doesn't make sense. You could fix this by doing:

if (myarray[key].hasOwnProperty('country')){
        arr.push(myarray[key].country)
    }
}

But it makes more sense to reduce the array instead:

const arr = myarray.reduce((a, c) => a.concat(c.country || []), []);

Comments

1

What you want to achieve isn't related to React specifically, It can be done using javascript functionality. On the other hand, you want to return the value of the specific key of each object inside of myarray

You can perform that using Array.prototype.reduce method like this

let myArray = [
  {'country': 'US', 'type': 'eat'}, 
  {'country': 'DE', 'type': 'test'}
];

const result = myArray.reduce((accumulator, current) => {
  return accumulator.concat(current.country);
}, []);

console.log(result);

of using Array.prototype.map like this

let myArray = [
  {'country': 'US', 'type': 'eat'}, 
  {'country': 'DE', 'type': 'test'}
];

const result = myArray.map(item => {
  return item.country;
});

console.log(result);

There many way to achieve the same result

Comments

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.