2

I try to read the value of the key color_ids in the following JavaScript associative array:

  const UrlArray = [
    {
      bd_shoe_size_ids: ["6601", "6598"]
    },
    {
      color_ids: ["6056", "6044"]
    },
    {
      manufacturer_ids: ["5875", "5866"]
    }
  ]

This was done by the following code:

UrlArray.find(({color_ids}) => color_ids); 

But I would like to use this code for reading the value of other array keys to. For that I want to store the name of the array key whose value I want to know in a variable. If I use the code below it will of course look for a key called nameOfArrayKey, but is it possible to search for the value of the variable: nameOfArrayKey?

UrlArray.find(({nameOfArrayKey}) => nameOfArrayKey);

4 Answers 4

1

I had the same problem. Try this:

console.log(UrlArray.map(Object.keys).flat())
Sign up to request clarification or add additional context in comments.

Comments

0

you can use hasOwnProperty property to check object has key name

function getObject(urlArray,nameKey){
  const object= urlArray.find(value=>{
     return value.hasOwnProperty(nameKey)
  });
  return object;
}

Comments

0

So, basically, you can try something like this :

const k = "manufacturer_ids"
console.log(UrlArray.find((o) => o[k]))

Output :

{ manufacturer_ids: [ '5875', '5866' ] }

Comments

0
function getObjectValueByKey (items, key) {
  const item = items.find(value => value.hasOwnProperty(key));
  
  if (item) {
    return item[key];
  }

  return null
}

const values = getObjectValueByKey(UrlArray, 'color_ids') // ['6056', '6044']

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.