1

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?

3
  • 8
    That's not even valid JS. Commented Jan 14, 2019 at 16:14
  • 3
    I have updated your code, just to show that syntax is not valid, you can run the snippet and check... Commented Jan 14, 2019 at 16:20
  • 2
    Arrays don't have keys in JavaScript Commented Jan 14, 2019 at 16:25

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.