Cannot Get JSON for the JavaScript Object [duplicate] - javascript

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>

Related

Get Value from JSON for a given Key where parent key names are dynamic [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 3 years ago.
I have a json string which starts like this:
{ "0" :
{"Jquery77768" :
{"nodeData":
{"id":32, "name": "Bob"}
----
I need to get the value which is there in the id key.
I tried to do something like this:
var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;
but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.
How can I get the value of the id field?
Since you mentioned dynamic key names (Jquery77768), It will be better to get the Object.values. (Assuming one key as in data).
var myID = Object.values(obj["0"])[0].nodeData.id;
What about a general function ? But suppose order of keys may not be same everywhere...
var obj = '{ "0" : {"Jquery77768" : {"nodeData": {"id":32, "name": "Bob"} }}}';
obj = JSON.parse(obj);
console.log(goDownNth(obj[0], 1).nodeData.id);
console.log(goDownNth(obj[0], 1).nodeData.id === goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 1));
console.log(goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 2));
function goDownNth (obj, n) {
for (var a in obj) {
if (!--n) return obj[a];
}
}

JavaScript to JSON with Keys [duplicate]

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 3 years ago.
I am trying to convert the parameters from my URL (Example 1) to a JSON Object that looks like Example 2. Unfortunately when I use JSON.stringify() it converts it to Example 3. Can anyone please point me in the right direction for splitting this? I am not sure how to get the keys out.
Example 1 - Input
food=apple,banana,peach&store=walmart&customer=John
Example 2 - Desired Output
{"food": ["apple", "banana", "peach"], "store":"walmart", "customer":"John"}
Example 3 - Current Ouput
{"food=apple,banana,peach", "store=walmart", "customer=John"}
Edits:
Forgot "" in food list
What I tried
data = "food=apple,banana,peach&store=walmart&customer=John";
data = JSON.stringify(data);
Using split, split the string appropriately and insert values in the object
var str = 'food=apple,banana,peach&store=walmart&customer=John';
var arr = str.split('&')
var obj = {};
for (let i = 0; i < arr.length; i++) {
var x = arr[i].split('=')
if (i == 0) {
obj[x[0]] = [];
x[1].split(',').forEach(function(y) {
obj[x[0]].push(y)
})
} else
obj[x[0]] = x[1]
}
console.log(obj)

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

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});

how to create array of json object without key in javascript

I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.

Merge Javascript objects, can't seem to find correct way [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 9 years ago.
Hi i've been struggling a bit and i cant seem to find why the methods i found dont work, could be "fixture-0"
First Object array
personformdata[i]: "{"isInvalid":false,"agentRole":"role"}"
Second
address_ids[i] : "[{"address_id": "fixture-0" }]"
preferable out come, something like this.
"{"isInvalid":false,"agentRole":"role", "address_id": "fixture-0"}"
you can do it like:
var mergedObj={};
for(var key in personformdata[i])
mergedObj[key]=personformdata[i][key];
for(var key in address_ids[i])
mergedObj[key]=address_ids[i][key];
or if you use jQuery:
var mergedObj={};
$.extend(mergedObj, personformdata[i], address_ids[i]);
I myself usually use vanilla JavaScript and prefer not using jQuery.
you can use :
var object = $.extend({}, object1, object2);
for xample you can visit this url.
http://api.jquery.com/jQuery.extend/
If you want to create a new array with merged objects, just do this with a for loop:
var newData = { };
for (var i = 0; i < personformdata.length; i++)
{
newData[i] = {
isInvalid : personformdata[i].isInvalid,
agentRole : personformdata[i].agentRole,
address_id : address_ids[i].address_id
};
}

Categories