Access object using dynamic object name [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I have an object with some data inside. The first level of data are 2 arrays (body, cause). Each body and cause array have arrays inside of them (date, year).
totals:[{body:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]},
{cause:[
{date:[54,9,3,17]},
{year:[437,61,31,140]}]
}]
What I would like to do is access the body/cause array dynamically based on something the user has changed.
This is how I am accessing them now.
totals[isCause].body[isYear].date[filterNumber]);
My issues is body and date are hard coded in there, and I would like to have access to either body/cause date/year. I can't seem to find what these property names are stored as. I tried to set up a var and do something like this
var bodyCause = "body";
Then I tried to pass it back into my retriever statement.
totals[isCause].bodyCause[isYear].date[filterNumber]);
But that fails. So I'm just trying to figure out what that property name is stored as and if I can dynamically set it when I need to retrieve information.

Your attempt was almost correct. You can easyly use var bodyCause = "body"; and access the content dynamically. Instead of this
totals[isCause].bodyCause[isYear].date[filterNumber]);
you should use this
totals[isCause][bodyCause][isYear].date[filterNumber]);
Should fix your problem.

Related

How do I assign a variable array name to be used in a foreach loop using javascript? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I have a script which receives a JSON formatted file as input and allows the user to call out a JSON object name for specific processing. I loop through the JSON file using a foreach() to process the specific items requested by the end user.
In this example The JSON input file has an object array called "socks". The requested JSON object name could be input by the user as "socks" as this would be the object they would like to have the code perform a function on.
I push all of these "socks" to a new array to perform the work on.
//working code
jsonDataIn.socks.forEach(function(s) {
newArray.push({ socks:s })
});
The above code functions as needed because I have hardcoded the array name as 'socks'. I cannot figure out how to assign the array name as a variable to apply the users input.
//I'd tried assigning just the array name as a variable, as well as both the data and array and those both are not valid.
let inputValueFromUser = 'socks';
let arrayNameVar=jsonDataIn.inputValueFromUser;
arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
nor this
let inputValueFromUser = 'socks';
let arrayNameVar=inputValueFromUser;
jsonDataIn.arrayNameVar.forEach(function(s) {
newArray.push({ [inputValueFromUser]:s })
});
In the above code the [inputValueFromUser] works for assigning the value to the newArray, but I cannot figure out how to get it to work inline as a form of 'jsonDataIn.inputValueFromUser.forEach()'. I found many examples if I were using multiple arrays in a forEach loop, but not how to pass the 'inputValueFromUser' as an array name.
I know it has to be a simple solution that I'm missing. Any assistance is appreciated.
All of the failed code that I've tried to make work has resulted in "TypeError: Cannot read properties of undefined (reading 'forEach')"

using . opearator inside backticks javascript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
So this is a bit of an unusual situation i am in but what i need to do is access the value of an object based on what index its stored in. The problem is that i need it in my Select component of material ui. So the overview is that i store alginment values of a video . the videos show up in a loop which means the select values are repeated and to know if its for the first video i append the index inside the object like this:
Now in order to set the option i have to access this value here :
Now the problem is in this loop i cant do something like :
halign.halign[index] because obviously that would mean its an array. So long story short how could i do something like :
value={`${halign.halign}${index}`}
So basically the end result for value to evaluate is : halign.halign0
and so on for each index.
NOTE the outer halign is the main useState object.
Remember that for JavaScript objects x['y'] and x.y are interchangeable.
So if you need to compute the key you're looking up, use:
halign['halign' + index]
Or template strings if you prefer.
Note this would be a lot easier if you organized your object with an internal array, so you could just do halign[index].

Use variable to access array results in undefined [duplicate]

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 5 years ago.
I am getting several arrays returned from a GET reponse, which I need to access. Since their names can change based on the request, I have a variable specifing which array to use.
However I always get undefined. See this:
console.log(current); // trips_out_201702
console.log(theResponse.current); // undefined
console.log(theResponse.trips_out_201702); // this works
How can I make theResponse.current work such that it returns what current actually stands for? Why do I get undefined there?
When the property key in an object is a variable you can use the square bracket notation to access that property.
console.log(theResponse[current]);
when acessing with dynamic attribute You should do as
theResponse[current] not theResponse.current
You are trying to get array value using object's way.
You should try this one instant variable['keyName']
Good Luck!

how to add key and a value to a json with same existing Key using Javascript [duplicate]

This question already has answers here:
How to add new property with same key name inside declared object?
(3 answers)
Closed 6 years ago.
I have a json variable like this
var jsondata={"key1":"val1", "key2":"val2"}
I want to push another object with same existing key, and i want that my variable will be like this
var jsondata={"key1":"val1", "key2":"val2", "key1":"val3"}
I tried jsondata["key1"] = "val3", but it didn't return the wanted result
Thank you in advance.
you cannot, as it is a map.
but you could create this json :
var jsondata={"Name":["Jhon","James"], "Age":40}
You can't use the same key in an object. Your question suggests that the logic behind your data structure is wrong.
An alternative:
Use a different field name, i've used "_Name" below, but perhaps "Second_Name" would be more appropriate. Unsure what your json data is modelling.
var jsondata={"Name":"Jhon", "Age":40, "_Name":"James"};
Or perhaps it makes sense to store an array of people, is that what you're trying to achieve? i.e. you have two people, with the names "Jhon" and "James"?
var jsondata={
"people": [
{"Name":"Jhon", "Age":40},
{"Name":"James"}
]
};

change key names of JSON using array [duplicate]

This question already has answers here:
JavaScript: Object Rename Key
(35 answers)
Closed 6 years ago.
Say I have some JSON data like this:
blah = [
{"Species":"setosa","Sepal.Length":5.1,"Sepal.Width":3.5},{"Species":"setosa","Sepal.Length":4.9,"Sepal.Width":3}
]
In my code, I won't necessarily know the key names of the JSON. Therefore, I can grab the keys like this (I do know that all elements of the array are identical in their keys):
mynames = Object.keys(blah[0]); // gives this... ["Species", "Sepal.Length", "Sepal.Width"]
I am able to change the name of the first key called Species here to newthing like this:
JSON.parse(JSON.stringify(blah).split('"Species":').join('"newthing":'));
But if I didn't know it was called 'Species', but knew it was the first element of 'mynames', I thought I could do the same thing like this:
JSON.parse(JSON.stringify(blah).split('mynames[0]:').join('"newthing":'));
or
JSON.parse(JSON.stringify(blah).split('"mynames[0]":').join('"newthing":'));
but both fail. Is there a way of doing this simply?
It seems what you want is
blah[0].newthing = blah[0][mynames[0]];
delete blah[0][mynames[0]];
but knew it was the first element of 'mynames',
Note that the order of keys is not guaranteed, so that might not work in every environment or even for multiple runs.
How do I remove a property from a JavaScript object? explains how the delete keyword can be used to remove properties. You can simply set the new property to the value of the old, then delete the old.

Categories