Ic3m4n
Ic3m4n

Reputation: 871

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?

Upvotes: 1

Views: 9454

Answers (3)

JO3-W3B-D3V
JO3-W3B-D3V

Reputation: 2134

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));

Upvotes: 2

CROSP
CROSP

Reputation: 4617

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.

Upvotes: 2

BairDev
BairDev

Reputation: 3211

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.

Upvotes: 0

Related Questions