Iterating though object in array in React (ES6) [duplicate] - javascript

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 5 years ago.
I have an object in array like the following:
bears: [
{
Yogi: "123kg",
Pooh: "110kg",
Grizly: "112kg",
BooBoo: "200kg",
Polar: "100kg",
}
]
`
What is the best way to iterate through such object in order to display both names and values in the row, like returning something in the type of: <p>${name} ${value}</p>
So I would display:
Yogi 123kg
Pooh 110kg
Grizly 112kg
BooBoo 200kg
Polar 100kh

It's an array containing an object, not an object. Anyway just get the first item of the array.
This should work:
Object.keys(bears[0]).map(key => <p>{`${key} ${bears[0][key]}`}</p>);

I think that the JSON object's structure itself is wrong.
It should be structured like this:
var bears = [{
name: "Yogi",
weight: "123kg"
}, {
name: "Pooh",
weight: "110kg"
}, {
name: "Grizly",
weight: "112kg"
}, {
name: "BooBoo",
weight: "200kg"
}]
Then you can go ahead and iterate through it using a for loop inside of the render() method like this.
render() {
var bearElements = [];
for (var bearIndex = 0; bearIndex < bears.length; bearIndex++) {
bearElements.push(
<p>{`${bears[bearElements].name}` `${bears[bearElements].weight}`}</p>
)
}
return (
<div>{bears}</div>
);
}

Related

I'm Unable to find out why array objects are repeating in my code [duplicate]

This question already has answers here:
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 4 months ago.
I'm trying to create a Array using json objects. But the last object is repeating in the array. I've mentioned that in the below code output. Can anyone help me finding the solution of this problem
This is the code
let list = [
{
'title':'alfa',
'item':'box',
'count':2
},
{
'title':'beta',
'item':'ball',
'count':4
}
]
let ev = {}
let ev_arr = []
for(let i in list){
ev.title = list[i].title
ev.item = list[i].item
ev_arr.push(ev)
}
console.log(ev_arr)
My output I got
[
{
'title':'beta',
'item':'ball'
},
{
'title':'beta',
'item':'ball'
}
]
Expected Output
[
{
'title':'beta',
'item':'ball'
},
{
'title':'alfa',
'item':'box'
}
]
You only ever have one object:
let ev = {}
The loop just over-writes the properties on that same object and re-adds that same object to the array. But there's still only ever one object.
Instead, create a new object in each iteration of the loop:
let list = [
{
'title':'alfa',
'item':'box',
'count':2
},
{
'title':'beta',
'item':'ball',
'count':4
}
]
let ev_arr = []
for(let i in list){
let ev = {} // <----- here
ev.title = list[i].title
ev.item = list[i].item
ev_arr.push(ev)
}
console.log(ev_arr)
To be honest, the code can be drastically simplified in general:
let list = [
{
'title':'alfa',
'item':'box',
'count':2
},
{
'title':'beta',
'item':'ball',
'count':4
}
];
let ev_arr = list.map(l => ({ title: l.title, item: l.item }));
console.log(ev_arr)
In this case you don't even need to manually create any objects or arrays as placeholders. You're just projecting an array into a new array using .map().

How to create array of objects from array: javascript [duplicate]

This question already has answers here:
How to convert array of items to array of objects?
(2 answers)
Closed 1 year ago.
I am trying to convert an array of elements to an array of objects in Javascript (react)
Here is the data I am getting from my API
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210" ]
And I am trying to convert to an array of object which should look like this
options = [
{ value: "1.0.1.2", label: "1.0.1.2" },
{ value: "1.0.22.0", label: "1.0.22.0" },
{ value: "2.5.2.6", label: "2.5.2.6" },
];
I tried using the map function
versions = VersionloginData.data.versions.map((version) => [version.value, version.label])
But didn't work out well , i am getting undefined as value objects
You needed to return an object inside the map callback:
versions = VersionloginData.data.versions.map((version) => ({ value: version, label: version }))
Its should be.
const data = {
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210"]
}
const output = data.versions.map(item => ({ value: item, label: item }));
console.log(output);
Why your code is not working?
You are accessing incorrect nodes with [version.value, version.label]. value and label doesnot exist on version. Instead, you should return an object with keys value and label having same value.
you can try this
var options = []
versions.forEach((v)=>{
options.push({
value: v,
label: v,
})
})

create object key and property of object dynamically [duplicate]

This question already has answers here:
How to set a Javascript object values dynamically?
(7 answers)
Closed 4 years ago.
I want to create a new object dynamically and insert into the inside of columns object
dynamicCreate = [
{
columns: {
title: {
title: "Title"
}
}
}
]
Create dynamically like
name: {
title: "Name"
},
and insert next of
title: {
title: "Title"
},
You can try using the dot notation
var obj={};
obj.title={};
obj.title.title="name";
console.log(obj)
Javascript is a dynamic language. so you can assign any props dynamically to the object.
var obj={
name:'foo'
};
obj.extraInfo={
bar:'baz'
}
console.log(obj);

Create id and check if it exists in an object array [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
How generate a unique id and push it through an object to an array, on condition that this id property value does not already exist in any of the array objects?
As per React code excerpt below, function "saveColor" was supposed to do that, attaching current state background color, so that an object would look similarily to those in the palettes array:
state = {
backgroundColor: "red",
palettes: [
{id: 2, color: "crimson"},
{id: 1, color: "skyblue"},
{id: 0, color: "rebeccapurple"},
{id: 4, color: "magenta"}
]
}
saveColor = () => {
let previousPalettes = this.state.palettes;
previousPalettes.push(this.state.backgroundColor);
this.setState({
palettes: previousPalettes
})
}
It is not clear why you need id here, but if you really need it - look at this package https://www.npmjs.com/package/uuid

Javascript - Get an object's name from another array [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 5 years ago.
This may be a really daft question or an impossible question..
I have a table which uses two arrays of objects like so:
const columnData = [
{ id: 'name', label: 'Name' },
{ id: 'value', label: 'Value' }
];
const rowData = [
{ name: 'Name 01', value: 100 },
{ name: 'Name 02', value: 150 },
{ name: 'Name 03', value: 200 },
];
I am writing this as a separate react component so I can reuse it and just change the two sets of data passed in as props. This is all fine and working, however I am struggling to figure out how to map the rows and columns to be dynamic.
i.e.:
...
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row.(THE_COLUMN_ID_TO_GET_THE_VALUE)}</td>
);
}
</tr>
);
}
...
I hope I make some sense here as it's a bit vague.. I basically want to get the value from rowData using the column id name. EG: <td>{row.name}</td><td>{row.value}</td> without hardcoding the item.
You can use the [] syntax on objects to obtain values based on computed properties.
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row[column.id]}</td>
);
}
</tr>
);
}
So you just want to get the property of the row that matches the column id? You can access a property with dynamic name using square brackets like row[column.id]
{this.props.rowData.map(row => {
return (
<tr>
{this.props.columnData.map(column => {
return (
<td>{row[column.id]}</td>
);
}
</tr>
);
}

Categories