Xiufen Xu Xiufen Xu - 1 month ago 7
Javascript Question

How to get values of json structure using javascript

I want to get the message by key-word in the json structure. For example, the json structure is:

[{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}


Now I want to get all the message and put them into an arrary. How to implement this in javascript? Thanks

Answer

You can use Array.map() or loop over the array and push the message to the array.

var a = [{ _id: 123, message: 'hello', username: '1' }, { _id: 456, message: 'world', username: '2'}];

var b = a.map(function(obj){
   return obj.message;
});

console.log(b);