How to set property of a pushed object within an array? [duplicate] - javascript

This question already has answers here:
Javascript pushing objects into array changes entire array
(8 answers)
Closed 4 years ago.
I have an object.
{
"header": [{
"items": []
}]
}
var jObj = jQuery.parseJSON('{"header":[{"items":[]}]}');
I push an object to the items
var align = jQuery.parseJSON('{"align":""}');
jObj["header"][0].items.push(align);
jObj["header"][0].items.push(align);
I set the values
jObj["header"][0].items[0].align = "right";
jObj["header"][0].items[1].align = "left";
console.log(JSON.stringify(jObj));
I get the same value for both aligns, how do I set the values?
Output
{"header":[{"items":[{"align":"left"},{"align":"left"}]}]}
This seems to work, but I need for it to by dynamic.
var jObj = jQuery.parseJSON('{"header":[{"items":[{"align":""},{"align":""}]}]}');

You are pushing a reference... Any change in one is reflected in the other. Try Object.assign({}, align) instead. It will create a copy without reference of the object.
var jObj = {
"header": [{
"items": []
}]
}
var align = {"align": ""};
jObj["header"][0].items.push(Object.assign({}, align));
jObj["header"][0].items.push(Object.assign({}, align));
jObj["header"][0].items[0].align = "right";
jObj["header"][0].items[1].align = "left";
console.log(jObj);
PD: Js treats json as array so there is no need of parsing.

Because align is the same Object, both the items point to the same reference when you set the property align they get overwritten..
jObj["header"][0].items.push(align);
jObj["header"][0].items.push({...align});

Related

Existing JSON getting updated if creating a new JSON from the existing one. Why is that happening? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 10 days ago.
I have an existing JSON and I take part of the JSON and modify it by creating a new JSON. Now, when I do a console.log of the existing JSON, it shows the existing JSON to have the updates done on the new JSON. Why is that happening ? (I'm doing this in React)
var newJSON = [];
let ifruleObject = oldJSON.rules[0].rules;
console.log(oldJSON);
ifruleObject.forEach((e) => {
for( var i=0; i<ifruleObject.length; i++)
{
if(ifruleObject[i].length <= 3)
{
ifruleObject[i]={ruleid:ifruleObject[i-1].id, rulecombinator: ifruleObject[i]};
newJSON .push(ifruleObject[i]);
}
}
});
console.log(newJSON);
In JS, objects store references. That means, if you assign an object to another variable, any changes made to that other variable will change the original object.
let obj = {a: 10, b: 20};
let copy = obj;
copy.a = 20;
console.log(obj);
console.log(copy);
In your code, you are storing the oldJSON.rules[0].rules object to ifruleObject. ifruleObject now references the original object at oldJSON.rules[0].rules. When you change ifruleObject[i], you are changing the oldJSON object implicitly (see above snippet).
You need to create a new object, copy the elements from the old object, and then assign the new object to your new object. Here is a possible implementation:
let temp = {ruleid: ifruleObject[i-1].id, rulecombinator: {...ifruleObject[i]}};
newJSON.push(temp);

Object properties in JavaScript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
I started to learn JavaScript, and I can not catch one thing.
myDog.name = "Happy Camper";
myDog["name"] = "Happy Camper";
and also
var myDog = {
"name" : "Coder",
"legs" : 4,
"tails" : 1,
"friends" : ["everything!]"
};
here in everything - what is the difference with and without brackets?
Thank you.
In JavaScript, [] is used to determine an Array literal, but is also one of the ways to call Object keys, hence your confusion.
const myArray = []; // Returns an empty array
const someObjectValue = myObject["myKey"] // returns the value of an object's key
Please note you can also fetch an object value by using dot instead of brackets:
// They are the same thing.
const value = myObject["myKey"];
const sameValue = myObject.myKey;
They're basically two different ways of achieving the same thing.
There is one difference, thought. With brackets you can assign otherwise non-allowed keys to objects.
Example:
const myObject = {};
// Set
myObject.0 = "Hello!"; // throws error
myObject[0] = "Hello!"; // works!
myObject.some-key = "Hello!"; // throws error
myObject["some-key"] = "Hello!"; // works!
// Get
const value = myObject.0; // throws error
const value = myObject[0]; // works!
const value = myObject.some-key; // throws error
const value = myObject["some-key"]; // works!
In the first case you are accessing data inside an object passing the key inside the brackets, in the second one using the brackets you are declaring an Array in javascript which is a list of data.
Checkout this definition of array:
Arrays are list-like objects whose prototype has methods to perform
traversal and mutation operations. Neither the length of a JavaScript
array nor the types of its elements are fixed
You could add more items into your array like:
var myDog = {
"name" : "Coder",
"legs" : 4,
"tails" : 1,
"friends" : [
"everything!",
"a little more",
"one more thing",
1,
"the previous element was a number",
"the next will be an object",
{name: "test"}
]
};
You can also access array data passing the key value inside brackets like objects but array keys are ordered numbers called index, for example.
const myArray = ["a", "b", "c"]
console.log(myArray[0]) // a
console.log(myArray[1]) // b
console.log(myArray[2]) // c
Click here for more info about arrays

Accessing a JSON key based on a lower level property in Javascript [duplicate]

This question already has answers here:
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I'm pretty sure this has been asked before, but I can't seem to find the solution, for lacking the appropriate words to describe the issue.
I'm trying to access an object's key (e.g. "ID1"), in an object of objects, according to the value of one of its lower keys (e.g. "name":"name1").
The JSON object contains different ID objects, each of which contains a name and other properties.
mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
It's pretty simple to get the name if I know the ID, e.g.:
myname = mydata["ID1"].name; //returns "name1"
But what I'm trying to do is get the ID of an object if I know its name, so in short, the reverse of the above line. Is there any simple solution for this (in pure Javascript or jQuery)? Note: I know the names are unique.
If I'm understanding you correctly, Object.keys() can help you. It would look something like this:
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
Object.keys(mydata).forEach(function(id) {
var obj = mydata[id];
if (obj.name === "name1") {
// I found an object based on the "name" property.
// the 'id' variable holds a reference to it.
}
});
var mydata = {
"ID1": {"name":"name1","akey":true,"anotherkey":"foor"},
"ID2": {"name":"name2","akey":true,"anotherkey":"bar"},
"ID3": {"name":"name3","akey":false,"anotherkey":"foo"}
}
var parentId = Object.keys(mydata).find(function(key){
return mydata[key].name === 'name2';
});
console.log(parentId);
The only way to do it, is to traverse over every property-value.
var result = null;
for(var key in mydata) {
if(mydata[key].name==='name1'){
result = key;
break;
}
}
console.log(result);

Cannot Get JSON for the JavaScript Object [duplicate]

This question already has answers here:
JavaScript associative array to JSON
(5 answers)
Closed 7 years ago.
I'm creating a JS object like this
var eleDetailsTop = new Array();
var j = 0;
var id = "ele"+j;
eleDetailsTop[id] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image"};
Now, I'm trying to convert this object to a JSON...
var fields = JSON.stringify(eleDetailsTop);
So, my problem is, this only gives an empty result.
Here is what I got when I debugged with FireBug
As you can see there is another object called wrappedJSobject inside this. If you checked inside it, you can see another wrappedJSobject as so on...
Why is this ? Why is this weird ?
You're creating an array and assigning it alphanumeric property.
Try this:
var j = 0;
var id = "ele"+j;
eleDetailsTop[j] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image"};
EDIT: If you do want to use id as property - defined eleDetailsTop as object:
var eleDetailsTop = {};
If you do:
var eleDetailsTop = {};
Then you can assign properties like
eleDetailsTop[id] = {}
But if you really need the array... that won't work because there's no associative arrays in js technically (they're objects).
<script>
var test = {};
test['iam1234'] = {};
console.log(test);
</script>

Define object with variables for property names [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Use a concatenated (dynamic) string as JavaScript object key? [duplicate]
(6 answers)
Shorthand way to construct JS object with variable property name [duplicate]
(2 answers)
Closed 9 years ago.
I have a problem in declaring a inicialiting an object. When I define an object and pass by reference a string does not recognize me and fails. The object is as follows:
markerGroups = {"america": [], "europa": [], "asia": [],"africa": [], "oceania": [] };
Well, it works correctly, but if I change, for example, "america" ​​putting var amer = "america"​​, like this:
var amer = "america";
markerGroups = {amer: [], "europa": [], "asia": [],"africa": [], "oceania": [] };
It does not work. What i have to do for resolve this?
In JavaScript, you don't need to quote your object keys. So amer: [] is creating the literal key "amer".
You need to use the [] method to do this:
var amer = "america";
markerGroups = {...};
markerGroups[amer] = [];
something like this;
var markerGroups = {}
var amer = "america";
markerGroups[amer] = [];

Categories