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);
CodePudding user response:
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;
}
CodePudding user response:
So, basically, you can try something like this :
const k = "manufacturer_ids"
console.log(UrlArray.find((o) => o[k]))
Output :
{ manufacturer_ids: [ '5875', '5866' ] }
CodePudding user response:
I had the same problem. Try this:
console.log(UrlArray.map(Object.keys).flat())
CodePudding user response:
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']
