change key names of JSON using array [duplicate] - javascript

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.

Related

How to add item to object JS [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I have looked all over google and i have found nothing that fits my needs. How would you add an item to an object. I basically have a string variable that i want as the key. Therefore i cant use obj.key = 'something';. I sort of want it like:
obj = {'somekey': 'somevalue'};
obj.add('someotherkey': 'someothervalue');
console.log(obj);
by obj.add() i mean someone's solution
and then console says {'somekey': 'somevalue', 'someotherkey': 'someothervalue'}
Does anyone know a way to do this. I don't care at what position it is just whether it is there. By the way i'm using node if that helps. If you have any questions on my code please ask.
Very simple:
obj["somekey"] = "somevalue";
You can also use a variable instead:
let myVariable = "somekey";
obj[myVariable] = "somevalue";
Or you just use normal object notation:
obj.somekey = "somevalue"

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].

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

Access object using dynamic object name [duplicate]

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.

Accessing an Object's properties in Javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
Hello I am doing a school assignment my main problem is as follows.
var objectQueue = {
customers:[
{name:"Phil", order:"coffee"},
{name:"Sandy", order:"coffee"},
{name:"Enrique", order:"sandwich"},
{name:"Joe", order:"coffee"},
{name:"Alex", order:"muffin"},
{name:"Zoe", order:"chili"},
{name:"Bahamut", order:"sandwich"},
{name:"Rydia", order:"timbits"}
]
};
I have this object, I need to know how to access each customer's order through a for loop. I can't get the loop to read each person's order. What would be the right way to do this?
This is where I am currently:
objectQueue[x]order
Assuming x is a counter:
objectQueue.customers[x].order
objectQueue has a property named customers, to access a simple property on a Javascript object, you can just use its name:
objectQueue.customers
Then, customers has a array of objects. To access elements in a array, we use its index:
customers[0]
Since the elements in the list are maps/objects, we can access them via properties as well:
customers[0].name
Putting this all together we get:
objectQueue.customers[0].name
Almost everything in Javascript is an object, so it's a little misleading to differentiate between arrays and objects (since arrays ARE objects), but I'm assuming you can dig into those details later if you're interested. In the meantime, this should get you going.
You first need to access the length of the customers and use that as your loop count, from there you can use 'i' your counter to access properties
for (i=0; i<objectQueue.customers.length; i++){
console.log(objectQueue.customers[i]);
console.log(objectQueue.customers[i].name);
console.log(objectQueue.customers[i].order);
}

Categories