I got an object of values which looks like this
const values = {
volume: {
length: "3",
height: "4",
width: "2"
}
}
and an array with the attribute labels belonging to the values. The array looks like this:
const attributes = [
{
id: "notImportant",
label: "notImportantFoo"
},
{
id: "length",
label: "LengthFoo"
},
{
id: "width",
label: "WidthFoo"
},
{
id: "height",
label: "HeightFoo"
}
]
I need to create a new array from all the values with the right label. The result should look like this:
const result = [
{
label: "LengthFoo",
reading: "3"
},
{
label: "WidthFoo",
reading: "4"
},
{
label: "HeightFoo",
reading: "2"
}
]
I tried to start by mapping all the Object keys of the values but since it is wrapped in another object I couldn't really access it.
CodePudding user response:
Something along the lines of:
const result = attributes.filter(x => x.id in values.volume)
.map(x => ({
label: x.label,
reading: values.volume[x.id]
}));
What are we doing here?
- Traversing the array of attributes
- Skipping values that do not exist in the object (
filter
) - Creating a projection that contains required data from both attribute definition and the real object (
map
)
CodePudding user response:
A combination of Object.entries()
and find()
will get you there:
const values = {
volume: {
length: "3",
height: "4",
width: "2"
}
};
const attributes = [{
id: "notImportant",
label: "notImportantFoo"
}, {
id: "length",
label: "LengthFoo"
}, {
id: "width",
label: "WidthFoo"
}, {
id: "height",
label: "HeightFoo"
}];
const result = Object.entries(values.volume).map(([id, reading]) => ({
label: attributes.find(v => v.id === id)?.label,
reading
}));
console.log(result);
CodePudding user response:
You can compile Array.forEach
, Object.keys
and Array.includes
to make it works.
Array.forEach
to loopattributes
array.Object.keys
to getlength
,width
,height
properties fromvalues.volume
.Array.includes
to filter the needed properties only.
You can check my below demo:
const values = {
volume: {
length: "3",
height: "4",
width: "2"
}
}
const attributes = [
{
id: "notImportant",
label: "notImportantFoo"
},
{
id: "length",
label: "LengthFoo"
},
{
id: "width",
label: "WidthFoo"
},
{
id: "height",
label: "HeightFoo"
}
]
var valueKeys = Object.keys(values.volume);
var result = [];
attributes.forEach(item => {
if (valueKeys.includes(item.id)) {
result.push({
label: item.label,
reading: values.volume[item.id]
});
}
});
console.log(result);