How to Map Array values from one Array to Another Array JavaScript?
15,482
Solution 1
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj =>{
var payload = {};
const mapping = [null, 'rt', 'do', 'f1'];
const key = mapping[obj.key];
payload[key] = obj.value;
return payload;
});
console.log(reformattedArray);
Solution 2
You could use a destructuring assignment and build a new object with computed property names.
For the final keys, you could use an object keys
with corresopnding keys to the the keys of the given object.
var kvArray = [{ key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }],
keys = { 1: 'rt', 2: 'do', 3: 'fi' },
result = kvArray.map(({ key, value }) => ({ [keys[key]]: value }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution 3
I'm not sure what format you want.
try the code below:
var kvArray = [{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 }];
var reformattedArray = kvArray.map(obj => obj.value);
console.log(reformattedArray)
the result will be:
[ 10, 20, 30 ]
Related videos on Youtube
Author by
codemt
Updated on May 28, 2022Comments
-
codemt almost 2 years
This is my Code. Where I want to Pass the Values of
kvArray
to Second Array.var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]; var reformattedArray = kvArray.map(obj => { var payload = {}; payload["rt"]; payload["do"]; payload["f1"]; payload[obj.key] = obj.value; console.log(payload["rt"]); return payload; });
The
console.log
is comingundefined
. Can anyone help here? I am pretty new to Map function.I want to Print this result.
payload["do"]=10 payload["f1"]=20 payload["f2"]=30
-
Lesleyvdp over 5 yearsYou are assigning payload[1], payload[2] and payload[3] when you are referring to obj.key in your map function. Thus payload["rt"] remains undefined.
-
NullPointer over 5 yearswhat value you want to store in payload["rt"] ?
-
Nina Scholz over 5 yearsplease add the wanted result as well.
-
codemt over 5 years@NullPointer i want payload["rt"] = 10.
-
Nina Scholz over 5 yearsbtw, it's quite unclear, if the wanted keys depends on the index or on the key values.
-
-
codemt over 5 yearsi have defined the keys of the array payload. and i want this output payload["rt"] = 10. like this.
-
codemt over 5 yearsthis is helpful:). thank you so much. Just to pass the keys of 'rt','do' to the payload, it is better to map them by declaring them in another array. thats sweet :)
-
Nurkartiko almost 4 years
const mapping = [null, 'rt', 'do', 'f1'];
what is null for?