I have an object values
:
JavaScript
x
10
10
1
values = [{
2
stringValues: "First value",
3
kind: "stringValues"
4
},
5
{
6
stringValues: "Second Value",
7
kind: "stringValues"
8
},
9
]
10
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:
JavaScript
1
8
1
{
2
"name": "name",
3
"abc": {
4
"def": "def",
5
"ghi": ["First Value", "Second Value"]
6
}
7
}
8
My approach is :
JavaScript
1
15
15
1
var valuesStr = "";
2
values.forEach(
3
(v) => {
4
valuesStr += `'${v.stringValues}',`
5
}
6
);
7
8
obj = {
9
name: "name",
10
abc: {
11
def: "def",
12
ghi: valuesStr,
13
},
14
};
15
But the result doesn’t look quite right:
JavaScript
1
8
1
{
2
"name": "name",
3
"abc": {
4
"def": "def",
5
"ghi": "'First value','Second Value',"
6
}
7
}
8
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.
JavaScript
1
15
15
1
var valuesArr = [];
2
values.forEach(
3
(v) => {
4
valuesArr.push(v.stringValues);
5
}
6
);
7
8
obj = {
9
name: "name",
10
abc: {
11
def: "def",
12
ghi: valuesArr,
13
},
14
};
15