Андрій Грін
Андрій Грін

Reputation: 41

Take object name from array

I have some object with name and variables.

var data = [ {   "id": 144,
    "name": "Zagreb",
    "region": "",
    "iso": "HR",
    "country": "Croatia"},
{   "id": 145,
    "name": "Wellington",
    "region": "",
    "iso": "NZ",
    "country": "New Zealand"}];

For render dropdown I need only "name" and "country".

But, object can have other names with variables. Which I know. So I have idea, write names that needs to render in array like.

var renderNames = ['name', 'country'];

At this moment i've stopped. I don't know how to get value from object using names from array. As I see, it's must be something like that:

data.name == data. (do something) renderNames[1];

Upvotes: 0

Views: 68

Answers (4)

Sede
Sede

Reputation: 61225

You can also use arrow function expression new in ES6

var data = [ {   "id": 144,
    "name": "Zagreb",
    "region": "",
    "iso": "HR",
    "country": "Croatia"},
{   "id": 145,
    "name": "Wellington",
    "region": "",
    "iso": "NZ",
    "country": "New Zealand"}];
data.map(element => element.name) // return an array of names
//[ "Zagreb", "Wellington" ]
data.map(element => element.country) // return an array of country
//[ "Croatia", "New Zealand" ]    
data.map(element => [element.name, element.country]) // return 2d array of name, country
// [ [ "Zagreb", "Croatia" ], [ "Wellington", "New Zealand" ] ]

or return an array of objects where properties are "name" and "country"

data.map( element => { return { "name": element.name, "country": element.country }; }) 

which yields:

[
        {
                "name" : "Zagreb",
                "country" : "Croatia"
        },
        {
                "name" : "Wellington",
                "country" : "New Zealand"
        }
]

Upvotes: 0

Pimmol
Pimmol

Reputation: 1871

If you want an array with objects including name and country, this can work:

var dropdowns = data.map(function(obj) {
    return {
    country: obj.country,
    name: obj.name
  };
});

https://jsfiddle.net/w0ggxc3m/

Upvotes: 1

gmaliar
gmaliar

Reputation: 5479

How about using Lodash? https://lodash.com

Then it's easy

_.map(data, function(obj) {
  return _.pick(obj, ['name', 'country']);
});

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

For render dropdown I need only "name" and "country".

If you want an array of names from this array

var names = data.map(function(value){return value.name});

similarly, for array of country

var countries = data.map(function(value){return value.country});

Upvotes: 2

Related Questions