Reputation: 102
I want to create an array of objects from the this.props.data, trying to do that i can't make the map put the key values which are normally generated by the object.entries.
I have a screenshot with the code, and some console logs and the results they show instead of {_key:"0"}, i want it to be {numberOfElements:"12"}. Thanks.
This is the problematic part of the code
import React, { Component } from 'react';
export default class DataTable extends Component{
render(){
const data= Object.entries(this.props.data).map((_key,_value)=>({
_key:String(_value)
}));
console.log(data)
console.log(Object.entried(this.props.data))
return <div></div>
}
}
Console Output :
Upvotes: 0
Views: 2100
Reputation: 935
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]) => ...);
Upvotes: 7
Reputation: 48
You should be composing an Object like this:
let object = {}; object[_key] = String(_value); return object;
Upvotes: 1