2

Say i have an array of objects in javascript as

var array=[{id:1,message:"hello",time:"00-00-0000"},{id:2,message:"sup",time:"00-00-0000"},...];

What is the best way to get an array only containing the message attribute. i.e.

var messages=["hello","sup",...];

3 Answers 3

8

The "best" way would be:

var messages = array.map(function(x) {return x.message;});

The most compatible way:

for(var messages=[],i=0,l=array.length; i<l; i++) messages[i]=array[i].message;
Sign up to request clarification or add additional context in comments.

14 Comments

I never heard of the map function. Nice touch!
so i guess the only way to do this is to iterate through all objects, i was trying to find something better than that
If you wanted to know the first or last word of every chapter in a book, you would have to do the same thing, go to each chapter and read the first or last word. How else would you do it?
@naveed why point at documents for jQuery when this was clearly an ECMA5 method? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@Xotic750 Sorry but I'm new to javascript and having only worked in c/c++, i thought it was possible because all you have to do is iterate through sizeof(object), like if your first string (char array with a fixed size in C) is at memory offset 10 and the sizeof the object is 100, then the second string will be at the offset 110, and the third at 210, but as the string over here has a dynamic size, so i guess that's not possible.
|
0
var messages = [];

for(var i = 0; i < array.length; i++) {
    messages.push(array[i][1]);
}

Comments

0

A terser, more modern variant on @Niet the Dark Absol's solution is:

const messages = array.map(x => x.message);

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.