ok so if you want an array of objects, each one representing one key/value pair of your original object, this will do the trick for you:
original = {
x : 2,
y : 3,
}
mapped = Object.entries(original).map(([_key, _value]) => ({[_key]: String(_value)}));
console.log(mapped);
if you need a new object with same key/values, but having the values mapped (for example by String()
), then this should work for you:
original = {
x: 2,
y: 3,
};
mapped = Object.entries(original)
.reduce((obj, [_key, _value]) =>
Object.assign(obj, { [_key]: String(_value) }),
{});
console.log(mapped);
and if you need the mapped object but inside an array, well, put it inside an array:
original = {
x: 2,
y: 3,
}
mappedInArray = [
Object.entries(original).reduce((obj, [_key, _value]) =>
Object.assign(obj, { [_key]: String(_value) }), {})];
console.log(mappedInArray);
also, generally speaking, note that you are doing this:
Object.entries(obj).map((_key, _value) => ...);
which is wrong, because entries is a list of pairs (arrays of length two, the first item being the key, the second item being the value), which when mapped, will go to your _key
parameter, and hence your _value
parameter would simply be the index of that key-value pair in the array of entries. i.e. you will get:
_key = [<first-key>, <first-value>]; _value = 0;
_key = [<second-key>, <second-value>]; _value = 1;
...
you should instead write that like this:
Object.entries(obj).map(([_key, _value]) => ...);
.map((_key, _value) => ( { [_key]: _value } ))
should do the trick