简体   繁体   中英

get object from array by key name

I want to get an object from an array by its key name.

Array:

 let input = [ id1: {}, id2: {}, id3: {}, ] console.log(input); 

And I only want the object with the key id2 . How can I filter the object from the array?

As @ritaj stated, in the code you provided, that was invalid syntax, I'm going to assume that you mean to implement something like this, via using the find function. However, if you want to find multiple objects, you could always use the filter function, as you can see in the second example, it's returning an array containing both the object with the property id2 and id3 .

 var array = [ {id1: {}}, {id2: {}}, {id3: {}}, ]; console.log(array.find(({id2}) => id2)); 

 var array = [ {id1: {}}, {id2: {}}, {id3: {}}, ]; console.log(array.filter(({id2, id3}) => id3 || id2)); 

First of all it is not a valid JS object or a JSON string.

If it is an object it should be defined as follows.

{
    "id1": {
        "some": "property"
    },
    "id2": {
        "some": "property"
    },
    "id3": {
        "some": "property"
    }
}

Let's call it parentObject .

In that case you can access the desired object simply by the property.

parentObject.id2 
or
parentObject['id2']

In case this is an array it should be defined as follows.

  [{
        "id1": {
            "some": "property"
        }
    },
    {
        "id2": {
            "some": "property"
        }
    },
    {
        "id3": {
            "some": "property"
        }
    }
  ]

Let's call it parentArray . And you can find it using the following code, for instance

var targetObject= parentArray.find(x => x.id2 !== undefined);

This will return the first match if it exists.

Arrays have numerical indexes only.

If you want only one single item of the array and you know the index:

var myArray = [{a: 'a'}, {b: 'b'}]
var iWantedIndex = 1;
var myObject = {};
myObject[iWantedIndex] = myArray[iWantedIndex];

If you need more complex checks or more than one element from the array you can use Array.prototype.forEach or a classic for-loop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM