4

how can I get value in an object array by a key, which is also in this object array.

the object array looks like this:

const objectArray = [
    {key: "1", value: "12321"},
    {key: "2", value: "asdfas"}
]

I have now the value of key, e.g. key = 1, but I want to get 12321 as result.

any solution?

5 Answers 5

5

You can use .find() to achieve it.

Try this:

Working Demo

this.objectArray.find(x => x.key == "1").value

To handle exception, if the item doesn't exists in the array, do this:

let item = this.objectArray.find(x => x.key == "1")
this.value = item ? item.value : null
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this using filter() and use the value of the key you already have.

const objectArray = [
    {key: "1", value: "12321"},
    {key: "2", value: "asdfas"}
]

const el = objectArray.filter(item => item.key == 1)[0];

el
  ? console.log(el.value) // gives 12321
  : console.log('none listed')

Comments

0

objectArray.find(e => e.key == "1")

ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Comments

0
objectArray.forEach(function(item) {
    Object.keys(item).forEach(function(key) {
        console.log("key:" + key + "value:" + item[key]);
    });
});

Comments

0

This question is dated, but I'm posting my response hoping it will help others.

This is what you need:

objectArray
    .filter((obj) => obj.key === key)
    .map((item) => {
        return item.value;
    }
);

Below is the fully functional code:

const objectArray = [
{ key: '1', value: '12321' },
{ key: '2', value: 'asdfas' },];



/* This function will return the value you're looking for. */

function getObjectValueById(key: string) {
    return objectArray
        .filter((obj) => obj.key === key)
        .map((item) => {
            return item.value;
        }
    );
}

Because your key is a string, I am using key: string in the function's argument. If your key is a number, then you can modify the function argument to key: number, and rest of the code will still work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.