agDev
agDev

Reputation: 865

Return key & value of property in object

I have an array of objects each object has some properties. how can i return only one property from all the object the key and the value together in an array?

Right now I'm only getting the values

This returns an array of objects:

var columnWidth = $('#grid').data('gridData').columns;

This return an array of values of a property named width from each object:

columnWidth.map(function(e) {return e.width;});

Now what im getting back is this:

[30, 50, 80, 80, 90, 125]

What I want to get back is:

["Width":30, "Width":50, "Width":80, "Width":80, "Width":90, "Width":125]

Upvotes: 0

Views: 308

Answers (1)

Pointy
Pointy

Reputation: 413717

Then just return those objects:

columnWidth.map(function(e) {return { width: e.width }; } );

That'll give you an array that looks like

[ { width: 30 }, { width: 50 }, ... ]

(Use Width: e.width if you want the property name capitalized.)

The format described in your question is not meaningful; there's no JavaScript data structure that looks like that, as array indexes are numeric. If you want a different structure, you may be able to do it with .map() or with .reduce().

This solution gives you an array of objects, each of which has a single property named "width". That seems like the closest approximation to your stated goal.

Upvotes: 4

Related Questions