Checking defined item in enum [duplicate] - javascript

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.

Related

Mapping to objects in a lambda function JavaScript - Why doesn't it work without parens? [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 2 years ago.
I am running the following in node and can't understand why one works and why the other doesn't. Here I have an array s where s = [1, 2, 3, 4]. I want to map each number to an object. I've been trying this for a long time:
s.map(i => {name: i})
which returns a list of undefined.
Finally I realized it worked with parenthesis:
s.map(i => ({name: i}))
This provides the output I want: [ { name: 1 }, { name: 2 }, { name: 3 }, { name: 4 } ]
I feel like there is a JavaScript concept I am not understanding. Why does this not work?
This is because => { represents a block function, not returning an object.
Wrapping the object in parentheses does nothing, it simply interrupts that pattern => {, meaning it's interpreted as a concise arrow function rather than a block arrow function, and you can return the object.
So, if you want to return an object, you can either wrap it in parentheses (this is the easiest way):
s.map(i => ({ name: i }));
Or use a block function:
s.map(i => {
return { name: i };
});
(on a side note, you can make your function more concise by passing in name as the map parameter name:
s.map(name => ({ name }));
As pointed out by Tomasz below, the reason that your first attempt returned a list of undefined was because name: is the syntax for a label in JavaScript - and you were just labelling name: then stating the variable i - so your code basically looked like this ES5:
s.map(function(i) {
name: i
// No return so it returns `undefined`
});

Having trouble understanding the map() method [duplicate]

This question already has answers here:
What is the concept of Array.map?
(10 answers)
Closed 3 years ago.
I have a class component that uses the map method to access an array of objects. I Then use an implicit return to turn each object into a component. From my understanding the map method can only take an array, then pass a function to change the array.I don't understand why my code below works?
class App extends Component {
state = {
players: [
{
name: "Guil",
id: 1
},
{
name: "Treasure",
id: 2
},
{
name: "Ashley",
id: 3
},
{
name: "James",
id: 4
}
]
};
render() {
return (
<div className="scoreboard">
{this.state.players.map( player =>
<Player
name={player.name}
id={player.id}
key={player.id.toString()}
removePlayer={this.handleRemovePlayer}
/>
)}
</div>
);
}
}
From MDN
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
The map() never change the original array but just create a new array according to the provided function.
In your code, the map() method creates a new array of Player components(the result of the provided callback).
The way you used is the same as what you said:"take an array, then pass a function to change the array".Here is the arrow function and an implicit return action.

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

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

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>
);
}

ReactJS/ React-Router: How to filter nested array and objects based on url path parameters?

I have the following set up:
Navigating to StudentsBoard:
<Link to={`/StudentsBoard/Kev/monday/blue`}></Link>
How route is set up:
<Route
component={StudentsBoard}
path='/StudentsBoard/:name/:day/:color'
/>
And on the StudentsBoard page:
const mapStateToProps = (state, ownProps) => {
let student = state.students.filter(student => student.name == ownProps.params.name)
let day = ownProps.params.day
let color = ownProps.params.color
return {
carFiles: student[0].day.color //Getting an error here saying day and color are - Uncaught TypeError: Cannot read property 'day'/'color' of undefined
}
}
But for let day and let color I'm getting an error: Uncaught TypeError: Cannot read property 'day'/'color' of undefined
How can I make the passed in params, day and color as references to the property in student[0]? Or is there a better way to filter an object based on parameters passed in via ownProps.params? Would like to ultimately get down to the color object.
Thank you and will be sure to vote up and accept answer
EDIT
Data structure:
students: [
{
name: Kev
monday: {
blue: {
room: 5
},
pink: {
root: 6
}
},
tuesday: {
green: {
room: 7
},
purple: {
root: 8
}
},
},
{
name: Jerome
monday: {
black: {
room: 5
},
orange: {
root: 6
}
},
tuesday: {
yellow: {
room: 7
},
purple: {
root: 8
}
},
},
]
As stated in a comment, you'll need to use
students[0][day][color]
What you did, was trying to access an object which would have to look like this:
var students = [{
day: {
color: {}
}
}]
Let me explain with an example:
student.monday
is the same as
student['monday']
Of course, the .monday version is more convenient, but when using ['monday'], it gives you the ability to swap 'monday' with the variable day, which represents a string, e.g. 'monday'.
var propertyName = 'monday';
student[propertyName];
You should generally use the .monday variant, whenever possible, and only use the brackets, if you have to (like in your case).
And you should also add some sort of error handling, if a property on your data structure does not exist. Since you are dealing with strings from a URL - which a user can alter - your code may break.
// check if day and color properties are available
// for that student
if(!students[0][day] || !students[0][day][color]) {
// either day or color does not exist on student
return { carFiles: null };
}
// All good, proceed as normal
Please note, that your component then would need to handle the case, where this.props.carFiles is null.
. and [' '] is an equivalence. But I don't understand why you used 'day' and 'color' here? There are no such fields in your data structure. Can you print them out in your console.log to view the day and color at first place before your parse them out from object?

Categories