14

I've got an array of objects with a few properties, such as 'value' and 'label'.

array.join(' ') of course gives me "[object] [object]", but instead I need to get a string of the 'value' properties of all objects, separated by a space.

What is the shortest way to do this, and is this possible without writing a for loop?

2
  • 1
    Are your objects alike? In other words, could they be made from a single constructor function? If so, then you could just add a .toString() method to your Constructor.prototype object to define how it should look when converted to a string. Then you can just do array.join(" ") Commented Aug 25, 2013 at 15:33
  • ...here's a demo. This would be nicer than having to manually map the array to new values to join. Commented Aug 25, 2013 at 15:38

2 Answers 2

28

Try using jQuery.map() - Array.map() not used because of IE < 9 support

For JSON.stringify() - use json2 for old browser support

$.map(array, function(obj){return JSON.stringify(obj)}).join(' ')

Update: To get the value properties

var string = $.map(array, function(obj){
    return obj.value
}).join(' ');

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

5 Comments

It seems you are missing return statement.
It seems I have badly explained. I edited my question, as what I need is a space separated string of all 'value' properties of the objects in the array.
@StevenDeGroote can you give an example for [{name: 'name1', age: 30, value: 'v1'},{name: 'name2', age: 27, value: 'v2'}]
I worked it out. I simply needed $.map(array, function(obj){return obj.value}).join(' '). Thanks for showing the way!
Note for those who are using an ES5 shim or don't care about IE8 or below and want to avoid jquery, the syntax is almost the same. Instead of $.map(array, function(... use array.map(function(...
8

Use Array.map:

let data = [
  {
    "animal": "cat",
    "name": "Fluffy"
  },
  {
    "animal": "dog",
    "name": "Bowser"
  },
  {
    "animal": "cat",
    "name": "Felix"
  }
]

Now extract the names using .map:

let names = data.map(item => item.name)


let nameString = names.join(' ')

And now nameString contains Fluffy Bowser Felix.

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.