Working with property accessors using string [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
How can I refer to a variable using a string containing its name?
(7 answers)
Is there a way to access a javascript variable using a string that contains the name of the variable?
(4 answers)
Closed 9 months ago.
I am trying to access a property’s value in an object, I know the name of the properties, but not the name of the object (if that makes sense).
This object name is retrieved from an array. Sorry I’m not very good with explaining things, but hopefully an example will help…
So for example…
const names = ["john", "ben", "doe"]
const john = {
age: 33,
hobby: "coding"
};
const ben = {
age: 25,
hobby: "soccer"
};
const doe = {
age: 20,
hobby: "playing games"
};
names.forEach((name) => {
console.log(name.age)
console.log(name.hobby)
});
So as you can see, I know what properties each object has, the object name I also know, but it is being passed in an array of strings.
When I run this code, it will log undefined, how would I be able to retrieve the age and hobby of each of the values in the array?

Related

How to destructure an object that contains key names with hyphen? [duplicate]

This question already has answers here:
How to destructure object properties with key names that are invalid variable names?
(3 answers)
Closed 2 years ago.
I'm trying to destructure this object:
{
name: "Bryan",
last-name: "Enid"
}
and this is not possible:
const {name, last-name} = req.body
Is there a way to destructure this, without changing the initial object key name?
You need to rename the variable, because minus is an operator and not part of a variable name.
BTW, name is a property of Window.name. if this is used you need to rename this value as well.
const { name, 'last-name': lastName } = { name: 'foo', 'last-name': 'bar' };
console.log(lastName);

String to access nested value from object in array [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
I have a somewhat strange question,
I would like to know if it is possible to use a string as an entire reference to get a value from an object within an array.
This is my array:
const myArray = [
{name: 'element1', id: 'elementid1'},
{name: 'element2', id: 'elementid2'}
];
where myArray[0]["name"] returns: 'element1'
Would it be possible to have this entire reference: myArray[0]["name"] as a string: 'myArray[0]["name"]' and use it to reference to this value.
So this: getViaString returns 'element1' with the following set up:
const getViaString = 'myArray[0]["name"]';
I have set up this fiddle as it probably explains better what I am trying to do:
jsfiddle
Thanks.
You could potentially use eval() - not recommended.
const getViaString = eval("myArray[0]['name']");
yes you can do it with
const getViaString = eval('myArray[0]["name"]');

How to print all the properties of the object in javascript? [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 4 years ago.
var object = { name: 'Harry', age: '25', sex: 'male'...... n};
This object has 'n' number of properties which I don't know and I would like to print these whole properties.
There are heaps of solutions from a quick Google, a recomended result is; Print content of JavaScript object?
console.log(JSON.stringify(object, null, 4));
The second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.
You can use the The Object.keys() function to get an array of the properties of the object:
var obj = { name: 'Harry', age: '25', sex: 'male'};
Object.keys(obj).forEach((prop)=> console.log(prop));

How to create new json object from exiting one? [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 7 years ago.
I want to create new json object from exiting one, because if I create from
var person1= { First Name: 'John',
Last Name: 'Smith',
age: 54,
dateofbirth: '31-08-68',
}
var person2=person1;
delete person2.age
This will also delete age from the person1, I don't want to delete age from person1, but person2. Because I need to initialize other person also. So How I create new json object from exiting object .
You must clone the object. The quick way is
var person2=JSON.parse(JSON.stringify(person1));

JavaScript Objects and for in loops [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
I'm working my way through a tutorial and I have hit a snag.
I created this object and I'm trying to loop through and print the first names of the entries. I thought it was working, but then I noticed that when I change 'firstName' in my for loop to 'number' or 'lastName', it still writes the first names to the console.
Can anyone shed some light for me? Thanks!
var friends = {
bill:{
firstName:"Bill",
lastName:"Gates",
number:"617-333-3333",
address:["One Microsoft Way", "Redmond", "WA", "98052"]
},
steve:{
firstName:"Steve",
lastName:"Jobbs",
number:"617-222-2222",
address:["15 Idontknow Street", "No Idea", "NO", "33333"]
}
};
var list = function(friends){
for (var firstName in friends) {
console.log(firstName);
}
}
The property names of your "friends" object are "bill" and "steve". That's what the loop iterates through — the property names. It doesn't matter what variable name you use.
What your loop is currently printing is "bill" and "steve", not "Bill" and "Steve". If you want to log the properties of the objects referenced by the properties of the "friends" object, you have to access those objects. If you wanted the "number" for example:
for (var fn in friends) {
console.log(friends[fn].number);
}

Categories