Given the following, how can I get the value for shape from the object to a variable?
var data =
[
{
"Category": "Color",
"Options": [
{
"Key": "color",
"Value": "red"
}
]
},
{
"Category": "Shape",
"Options": [
{
"Key": "shape",
"Value": "circle"
}
]
}
];
var shape = // want this to be 'circle'
if you need the whole object you can use find or you can use reduce to get just what you need or you can get all the options with flatMap and than find the option you need
var data =
[
{
"Category": "Color",
"Options": [
{
"Key": "color",
"Value": "red"
}
]
},
{
"Category": "Shape",
"Options": [
{
"Key": "shape",
"Value": "circle"
}
]
}
];
const shape = data.find(d => d.Category === 'Shape')
const shapeOption = data.reduce((res, d) => {
if(d.Category === 'Shape'){
return d.Options.find(o => o.Key === 'shape').Value
}
return res
}, null)
const shapeWithTransformations = data.flatMap(d => d.Options).find((o) => o.Key === 'shape').Value
console.log(shape)
console.log(shapeOption)
console.log(shapeWithTransformations)
In your case it will be
var data =
[
{
"Category": "Color",
"Options": [
{
"Key": "color",
"Value": "red"
}
]
},
{
"Category": "Shape",
"Options": [
{
"Key": "shape",
"Value": "circle"
}
]
}
];
const shape = data[1]['Options'][0]['Value'];
console.log(shape);
But your structure is over complicated, if you have control over it then it should be something like
const data =
{
'Color': {
'Key': 'color',
'Value': 'red'
},
'Shape': {
'Key': 'shape',
'Value': 'circle'
}
};
const shape = data['Shape']['Value'];
console.log(shape);