How to set the named index of associative array dynamically? [duplicate] - javascript

This question already has answers here:
JavaScript set object key by variable
(8 answers)
Closed 3 years ago.
I am trying to create an array with the following data as example. I want to set the named index dynamically based on the user selected value. But when I set the index to a variable, the declared variable name is considered a string in the array and set as the array index name.
var country = userInputFromUi;
var cities = [a,b,c,d];
array.push({
country:cities
})
Expected result
userInputFromUi:[a,b,c,d]
actual result
country:[a,b,c,d]
Not sure if I am understanding something wrong here.

Use computed property names like so:
array.push({ [country]: cities });

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')"

Javascript: change object key and value [duplicate]

This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Closed 2 years ago.
I have an object that I receive from an api, and each object's length are similarly long.
now, it does have a key fname and lname and I want it to become just name. I don't want to manually create an empty array and push a new one there just to change fname and lname into name.
Is there anyway I can achieve this without looping through the object and manually pushing it?
You can destructure the object while mapping it, here I have created a dummy data, let me know if this is something what you need:
var array=[{id:1, fname:'Bob', lname: 'Alice', someotherkey:'key'}];
var result = array.map(({fname, lname, ...rest})=>({name:fname+' '+lname, ...rest}));
console.log(result);

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"}
]
};

How can I use a key value as a variable name in JavaScript? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 6 years ago.
I want to be able to take JSON into my program and then create objects based off of that data. So, I want to create objects where the name of that object is the value stored in a key value pair. For instance, if I had the following JSON (and I know this isn't perfect JSON):
{
"objectName" : "**variableName**",
"someDataName" : "thatData",
"someOtherDataName" : "thisData"
}
Then I want to be able to make an object like this:
function myObject(thatData, thisData) {
this.name = name;
this.thatData = thatData;
}
var **variableName** = new myObject(thatData, thisData);
The key here is that I want to be able to use the value stored in the ObjectName key value pair as the variable name for the object. Is this even possible? I have been looking for how to do this for a while now. I believe that this is different than "Variable" variables in Javascript? because I am trying to use a value in a key value pair to name my objects.
If I understand correctly what you're trying to do here, one approach may be to set properties within a variable:
let myContainer = {};
// ...
myContainer['whatever_variable_name'] = new ...
You can how use myContainer.whatever_variable_name or myContainer['whatever_variable_name'] to access the new object.
To assign properties from JSON objects, see Object.assign.
You can use the property accessor on the window object to set the value for a dynamic key on the global scope.
var window["**variableName**"] = new myObject(thatData, thisData);

Updating a result in JSON with a dynamic variable name [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I need to update a value in my JSON.
My JSON result looks like this:
results = {"ROWCOUNT":50,"COLUMNS":["PERSONID","NAME"],"DATA":{"PERSONID":["42","43","44"], "NAME":["JOE","TOM","JANE"]}
resultData = results.DATA
In the below code I am looping over the result set and attempting to update a value at a position. I believe it is failing because I am not using dynamic variables correctly.
var columnName = "NAME";
for(i=0; i < results.ROWCOUNT; i++ ){
resultData.columnName[i] = "foo" // failing here due to "columnName" being dynamic.
}
Figured it out.. You have to use array syntax
resultData[columName][i]

Categories