How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render poents for each one passing in the both the name and data?
How can I convert to array of objects that will keep both the name and data "a", "b" so I can map and render poents for each one passing in the both the name and data?
javascript
reactjs
Share
Improve this question
edited Jun 7, 2018 at 12:09
Red
7,3441010 gold badges5252 silver badges9595 bronze badges
asked Jun 7, 2018 at 11:59
AlmogAlmog2,84777 gold badges3535 silver badges7171 bronze badges3
3Please add the desired output
– Nikhil Aggarwal
CommentedJun 7, 2018 at 11:59
What's the expected output, or rather how do you plan to structure the result? Regardless, the solution most likely involves Object.keys()
– ionizer
CommentedJun 7, 2018 at 12:07
I need to pass both the left and right data, if I use object keys I only get the data like b or a but I also need name 1 or name 2 with it
– Almog
CommentedJun 7, 2018 at 12:24
Add a ment
|
4 Answers
4
Reset to default
5
If you use a reduce function you can do the following to achieve your goal
Reduce is a cool function that iterates and bine data into one single item (could be 1 object, array, integer, etc).
Object.keys() is a way to get each key from the current object and be able to iterate over each.
The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
so you can try something like this
let result = Object.entries(data);
result.map((item, index)=>{
console.log('key is:- ', item[0], ' and value is:- ', item[1]);
});
you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.
This will convert to array of objects that will keep both the name and data.
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
}
var res = Object.keys(data).map(function(name){
var obj = {};
obj[name] = data[name];
return obj;
});
console.log(res);
js native method u can use;
var data = {
"name 1":"a",
"name 2":"b",
"name 3":"b",
};
var newObj = [...Object.values(data), ...Object.keys(data)]
console.log(newObj)