I have an object values:
values = [{
stringValues: "First value",
kind: "stringValues"
},
{
stringValues: "Second Value",
kind: "stringValues"
},
]
I need to extract the stringValues and put them into another object obj as a value to the key ghi. The final result should look like that:
{
"name": "name",
"abc": {
"def": "def",
"ghi": ["First Value", "Second Value"]
}
}
My approach is :
var valuesStr = "";
values.forEach(
(v) => {
valuesStr += `'${v.stringValues}',`
}
);
obj = {
name: "name",
abc: {
def: "def",
ghi: valuesStr,
},
};
But the result doesn’t look quite right:
{
"name": "name",
"abc": {
"def": "def",
"ghi": "'First value','Second Value',"
}
}
As you can see, it puts both values as 1 string.
Fiddle: https://jsfiddle.net/zrx0sp76/
Advertisement
Answer
Well if you want it be an array, then declare it as an array and push() values to it.
var valuesArr = [];
values.forEach(
(v) => {
valuesArr.push(v.stringValues);
}
);
obj = {
name: "name",
abc: {
def: "def",
ghi: valuesArr,
},
};