JSON.stringify multidimensional [duplicate] - javascript

This question already has answers here:
JavaScript associative array to JSON
(5 answers)
JSON.stringify doesn't work with normal Javascript array
(6 answers)
Closed 4 years ago.
I am trying to send a javascript object to PHP using JSON.stringify and I cannot find a solution. Here`s an example of what I have:
var small_array = [],
final_array = [];
small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";
final_array.push(small_array);
console.log(JSON.stringify(final_array));
The output is "[[]]"
Any guidance on this one? Thanks

You're adding non-array-entry properties to the array. That's fine in JavaScript, but JSON doesn't have the notion of non-array-entry properties in an array (JSON arrays are just ordered sequences, whereas in JavaScript arrays are fully-fledged objects that provide special treatment to certain kinds of properties — more in my [ancient] blog post A Myth of Arrays).
For those property names (keys), you'd want a plain object, not an array:
var obj = {}, // Note {}, not []
final_array = [];
obj["ok"] = "ok";
obj["not_ok"] = "not_ok";
final_array.push(obj);
console.log(JSON.stringify(final_array));

There are no associative arrays in javascript. They are called objects:
const smallObject = {
ok: "not ok",
not_ok: "ok"
};
const finalArray = [smallObject];
console.log(JSON.stringify(finalArray));

Objects in javacript are defined like this var obj = {}
var small_array = {},
final_array = {};
small_array["ok"] = "ok";
small_array["not_ok"] = "not_ok";
final_array = (small_array);
console.log(JSON.stringify(final_array));
VM1623:9 {"ok":"ok","not_ok":"not_ok"}

Related

How to compare two different Object keys and update it's value if keys are same in Javascript? [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 2 years ago.
Here i am having two different objects :
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
result should be comparing this above two objects and check if the key are same , then update the oldObject value with newObject . The result has to be like this
let updatedObject = {name:"Dhanush kumar S",age:23,sex:"Male",education:"Btech"}
I tried by doing something like this, but this doesnt help. Your help is much appreciated.
const compareObjects = () => {
for (let [key,value] in oldObject) {
if (newObject.hasOwnProperty(key)) {
oldObject[newObject[key]] = newObject[value]
delete oldObject[key]; //remove old entry
}
}
console.log(oldObject)
}
compareObjects()
You can do this by using the spread syntax.
Just spread the old object first followed by the new object.
Matching keys if any would be updated by the values from the new object and new keys in the new object would be added:
let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}
const merge = (oldObj, newObj) => {
return {...oldObj, ...newObj};
}
console.log(merge(oldObject, newObject));

Using an object clone method and a for loop to push objects into array, the objects are all still the same reference and are the same in the array [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 2 years ago.
let promiseArr = [];
for (let i = 0; i < ISOarr.length; i++) {
options.body.start_time = ISOarr[i];
let newOptions = cloneOptions(options);
promiseArr.push(newOptions);
}
console.log(promiseArr);
Returns an array of the same object.
Clone method:
cloneOptions = options => {
let clone = {};
for( let key in options ) {
clone[key] = options[key]
}
return clone;
}
So my question is how do I push an object that is not the same reference as the previous objects pushed, because even with it supposedly creating a new clone each loop it still somehow creates the same referenced object.
In the loop if I console.log I get the proper output with the value of the key changed, but once it's pushed into the array and we console.log the array, all objects are the same. Any suggestions would be super helpful. Thank you in advance!
Can you try this
cloneOptions = options => {
return JSON.parse(JSON.stringify(options))
}

Using reduce() changes order of array [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 4 years ago.
Within the example script I have generated two arrays I would like to combine to a single row:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
and
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
What I am trying to achieve is a string like { aLabel = aValue, bLabel = bValue, ... } that can be used to upload into BigQuery (the data upload job works).
I found a piece of code that almost does this, but somehow it changes the order of the elements within the two arrays.
var code = testValue.reduce(function(obj, value, index) {
obj[testHeaders[index]] = value;
return obj
}, {})
However, the result does mix up the order of the arrays as seen below. I am not capable of figuring out why the order changes. As far as I know, reduce() should work its way from left to right in an array.
The returned object is:
{
aLabel = aValue,
dLabel = dValue,
bLabel = bValue,
eLabel = eValue,
cLabel = cValue
}
You can use map and join:
var testHeaders = ["aLabel", "bLabel", "cLabel","dLabel","eLabel"];
var testValue = ["aValue","bValue", "cValue","dValue","eValue"];
var res = '{' + testHeaders.map((label, i) => `${label}=${testValue[i]}`).join(',') + '}';
console.log(res);
As vlaz pointed out, you are creating neither a string or a new array, but an object. And just like maps, objects do not have a set order of keys in JavaScript. hence, there is quite a chance of getting another order in the object than in both arrays.

Convert object key-value pairs to a series of arrays in Javascript [duplicate]

This question already has answers here:
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 2 years ago.
I am new to Javascript. I have a Javascript object like so:
s = {"Toothless":"Dragon","Foo":"Bar"};
I need to convert it into a series of arrays, like so:
out = [["Toothless","Dragon"],["Foo","Bar"]];
This is the reverse of what is discussed in Convert JavaScript array of 2 element arrays into object key value pairs. A JQuery solution is acceptable.
You can map over the items to achieve this:
s = {"Toothless":"Dragon","Foo":"Bar"};
var out = Object.keys(s).map(function(data){
return [data,s[data]];
});
console.log(out);
let s = {"Toothless":"Dragon","Foo":"Bar"};
let out = Object.entries(s);
and you get out as an array of small arrays,
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
var s = {"Toothless":"Dragon","Foo":"Bar"};
var out = [];
for (var key in s){
out.push([key, s[key]]);
}
Try this using jQuery.
var tempArr = [];
s = {"Toothless":"Dragon","Foo":"Bar"};
$.each(s,function(i,v){
tempArr.push([i,v]);
});

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