Raymond the Developer
Raymond the Developer

Reputation: 1676

How to select an object inside array that has a specific value in JS

How do I select an object inside an array where the object has the the value "A" for the "slug" key?

for example if I have this:

 var allItems = [
    {
        "slug": "henk",
        "company_founded": "2008",
        "company_category": "Clean",
        "company_logo": false,
        "company_description": "",
    }
    {
        "id": "bas",
        "company_founded": "2012",
        "company_category": "Health",
        "company_logo": false,
        "company_description": "",
    }
    {
        "slug": "jan",
        "company_founded": "2005",
        "company_category": "Clean",
        "company_logo": false,
        "company_description": "",
    }
]

What I want is to put the object that contains the slug : henk inside a new variable.

So I will have something like this to work with:

var = SelectedItem = {
    "slug": "henk",
    "company_founded": "2012",
    "company_category": "Health",
    "company_logo": false,
    "company_description": "",
}

Thanks!

Upvotes: 1

Views: 5381

Answers (5)

Fire Crow
Fire Crow

Reputation: 7739

You may consider storing the values in an object indexed by the expected keys, such as:

var allItems = {
  "henk":
    {
        "slug": henk,
        "company_founded": "2008",
        "company_category": "Clean",
        "company_logo": false,
        "company_description": "",
    },
  "bas":
    {
        "id": bas,
        "company_founded": "2012",
        "company_category": "Health",
        "company_logo": false,
        "company_description": "",
    }
]

this allows you to retrieve a value like allItems.henk

it indexes faster because it's a logarithmic hash-table look up instead of a full iteration.

----- edit ----

if you need to transform it in advance to accelerate lookup, as long as the cost of generating the new structure is less than the cost of the lookups you will be doing. you can do,

var allItemsByKey = {}
for(var i = 0, l = allItems.length; i<l; i++){
   var item = allItems[i];
   allItemsByKey[item.slug] = item;
}

then allItemsByKey has the structure demonstrated above

Upvotes: 1

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

Make it consistent: Array of objects (put comma between, changed id to slug to match others.)

Assumption is that the property is unique OR it will get the LAST ONE in the list. Like an ID lookup or some such.

EDITED to show value within complex object vs simple array EDIT2: add second lookup by category

var allItems = {"fred":"H fred",rats:"rats",lookupitems: [{
  "slug": "henk",
  "company_founded": "2008",
  "company_category": "Clean",
  "company_logo": false,
  "company_description": "",
} ,{
  "slug": "bas",
  "company_founded": "2012",
  "company_category": "Health",
  "company_logo": false,
  "company_description": "",
}, {
  "slug": "jan",
  "company_founded": "2005",
  "company_category": "Clean",
  "company_logo": false,
  "company_description": "",
}]};

Create a lookup we can use in a repeatable fashion:

var lookup = {};
var lookupbycategory = {};
// create reference to list above and use it everywhere
lookup.list = allItems.lookupitems;
for (var i = 0, len = lookup.list.length; i < len; i++) {
  lookup[lookup.list[i].slug] = lookup.list[i];
  lookupbycategory[lookup.list[i].company_category] = lookup.list[i];
}

Get one (use it)

var mychoice = lookup["henk"];
alert(JSON.stringify(mychoice));
alert(JSON.stringify(lookupbycategory["Clean"]));

reuse it

var mybas = lookup["bas"];

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386848

For mixed up object, you can iterate over all properties and return only the object which some propertiy has a certain value.

var allItems = [{ "slug": "henk", "company_founded": "2008", "company_category": "Clean", "company_logo": false, "company_description": "", }, { "id": "bas", "company_founded": "2012", "company_category": "Health", "company_logo": false, "company_description": "", }, { "slug": "jan", "company_founded": "2005", "company_category": "Clean", "company_logo": false, "company_description": "", }],
    result = allItems.filter(function (a) {
        return Object.keys(a).some(function (k) {
            return a[k] === 'henk';
        });
    });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Upvotes: 1

MinusFour
MinusFour

Reputation: 14423

You might want to look up into Array.prototype.find:

 var obj = allItems.find(function(el){
     return el.slug === 'henk';
 });

Upvotes: 1

Stefan Falk
Stefan Falk

Reputation: 25517

You will have to iterate your list and based on your condition take the element that you are looking for:

var result;
for each (var item in allItems ) {
    if(item.company_founded === "2012") {
        result = item; 
        break;
    }
}

Upvotes: 1

Related Questions