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
Related
This question already has answers here:
React doesn't rerender on an array state update
(2 answers)
React re-render not showing updated state array
(3 answers)
Correct modification of state arrays in React.js
(19 answers)
Right way to clone objects / arrays during setState in React
(7 answers)
Why is useState not triggering re-render?
(9 answers)
Closed last month.
I have an object employees that gets updated from user input through setEmployees() inside a function. I don't understand why for loop does not work but map() works to update the value on the webpage. I am not sure if this is react thing or useState() thing or maybe something else that I missed or did not know. Any idea? Thank you.
The employee object that gets updates from useState hook:
const [employees, setEmployees] = useState([
{
id: 0,
name: "Jason",
role: "Engineer",
img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
},
{
id: 1,
name: "Abby",
role: "Manager",
img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
}
]);
The case where I use for loop but it does not work:
function updateEmployee(id, newName, newRole) {
// Using for loop to update values
const updatedEmployees = employees
for (let i of updatedEmployees) {
if (i.id == id) {
i.name = newName
i.role = newRole
}
}
console.log(updatedEmployees) // updatedEmployees has been successfully updated
setEmployees(updatedEmployees) // object `employees` values have been updated but the update does not show on the webpage
}
The case where I use map() and it works:
function updateEmployee(id, newName, newRole) {
// Using map() to update values
const updatedEmployees = employees.map((employee) => {
if (id == employee.id) {
return {...employee, name: newName, role: newRole}
}
return employee
})
setEmployees(updatedEmployees) // object `employees` values have been updated and also update the values shown on the webpage
}
This question already has answers here:
How to deep merge instead of shallow merge?
(47 answers)
Closed 2 years ago.
I have a json object containing information about a person, and I want to update the data using jQuery extend function, the problem is that the child gets rewritten.
example:
var dadThen = {
name: "Adam",
age: 35,
child:{
name: "Ben",
age: 10
}
}
// dad now
var dadNow = {
age: 36,
child: {
age: 11
}
}
var newData = $.extend({}, dadThen, dadNow);
// The child name gets removed
// newData.child.name is undefined
How to fix this?
Isnt it like this
var newData = $.extend(true, {}, dadThen, dadNow);
first parameter is a flag whether to deep clone the object.
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);
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>
);
}
This question already has answers here:
How do I check if an object has a specific property in JavaScript?
(31 answers)
Closed 5 years ago.
I have an enum in which I store some UI element values that look like this:
const uiElementAttributes = {
1: {
id: 1,
color: 'red',
icon: 'icon-something.png'
},
2: {
id: 2,
color: 'yellow',
icon: 'icon-something-else.png'
},
3: {
id: 3,
color: 'blue',
icon: 'icon-this-item.png'
},
99: {
id: 99,
color: 'black',
icon: 'icon-black.png'
}
};
I have a function that will return the correct object from the enum based on id passed to my function. My question is how do I check if a value is defined in an enum?
Here's the function:
const getAttributes (id) => {
// How do I check to see if the id is in the enum?
if(checkIfIdIsInEnum) {
return uiElementAttributes[id];
} else {
return uiElementAttributes[99];
}
};
UPDATE: I'm trying the suggested answer. It does look pretty straight forward but looks like when webpack transpiles my code to vanilla JS, it adds default at the end of my enum which is undefined. Any idea what may be causing this -- see below? As you can see, the id value I'm passing is 1 so it should be able to find the value 1 in my enum object.
And here's the actual enum object:
Here's the actual function code:
UPDATE 2:
I resolved the issue by importing the enum within curly braces -- see below:
import {calendarEvents} from '../../enums/calendarEvents';
In this special case, you could access the property and if the result is falsey, then take the default property 99.
const getAttributes = id => uiElementAttributes[id] || uiElementAttributes[99];
Otherwise, you could use the in operator, or the suggested Object#hasOwnProperty.