JSON object to Javascript Array [duplicate] - javascript

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to know what is the fastest function that can be used to convert a json object into a java script array here an example
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr ===> [var1] = "val1"
The bottom line is to avoid for loops as much as possible

Most modern browsers will support the native JSON.parse function.
var arr = JSON.parse('[{"var1":"val1", "var2":"val2"}]');
console.log(arr);
//Just to be clear for OP
console.log(Array.isArray(arr)); //true
I want the output to be Arr[var1] = "val1"] not [Object]
That means you want to object at index 0 in the array.
var obj = JSON.parse('[{"var1":"val1", "var2":"val2"}]')[0];
console.log(obj['var1']); //val1
If you only want the values:
var values = JSON.parse('[{"var1":"val1", "var2":"val2"}]').reduce(function (values, obj) {
for (var k in obj) values.push(obj[k]);
return values;
}, []);
console.log(values); //["val1", "val2"]

If I understand you correctly, you can use JSON.parse.
var json = '[{"var1": "val1", "var2": "val2"}]';
var arr = JSON.parse(json);

I usually use jQuery, though that might no longer be preferred.
var j = '[{"var1":"val1", "var2":"val2"}]';
var arr = jQuery.parseJSON( j );
This should work well in some older browsers if you need that kind of thing of course.

Related

Convert array of items to key value [javascript] [duplicate]

This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 2 years ago.
My array is something like this:
languages: ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...]
I want to convert it so that it looks like:
languages: [{id:0,"Afrikaans"},{id:1,"Albanian"},{id:2,"Arabic"},{id:3,"Azerbaijani"}, {id:4,"Bengali"},...]
Build an object in each iteration step and then return this obj to build the result array.
I have added a key for your languages because otherwise it isn't valid syntax.
let languages = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"]
let res = languages.map((x, ind) => {
let obj = {
"id": ind,
"lang": x
}
return obj;
})
console.log(res);
A simple for loop does the trick here, and your final result is an array filled with incorrectly formatted objects so I took the liberty of adding the language property as you can see.
Let listOfLanguagesArray be your first array and finalArray be your result
var listOfLanguagesArray = ["Afrikaans","Albanian","Arabic","Azerbaijani", "Bengali"...];
var finalArray = [];
for (var j = 0; j < listOfLanguagesArray.length; j++) {
finalArray.push({
id: j,
language: listOfLanguagesArray[j]
});
}
It does seem that, however, what you're asking for is tedious and unnecessary work because you can traverse an array with more efficient methods than traversing an array of objects for the same information in the same order.

JSON.stringify multidimensional [duplicate]

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

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

Iterate through dictionaries in javascript and access values? [duplicate]

This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I am not a javascript expert, so I am sure what I am trying to do is pretty straight forward, but, here it is:
I have an array that comes down from a database, it looks like this:
[{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}]
I want to iterate through all dictionaries found in the array and access the aName, aLastname etc... so all possible values found in each dictionary, a dictionary at the time.
I tried using eval(), I tried to use JSON.parse, but JSON.parse I think was complaining because I think the object was already coming down as JSON.
How can I do that in javascript?
Thanks
So then I tried to do what was suggested by the "duplicate" answer comment... I did this:
for(var i=0; i<array.length; i++) {
var obj = array[i];
for(var key in obj) {
var value = obj[key];
console.log(key+" = "+value);
}
}
Problem is that the log is out of order. I get this:
name = aName
name = bName
lastName = aLastName
lastName = bLastName
I want to be sure I iterate through the properties and values in order one dictionary at the time.
What am missing here?
var test = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
for (var i = 0; i < test.length; ++i) {
alert(test[i].name + ", " + test[i].lastName);
}
http://jsfiddle.net/1odgpfg4/1/
You may want to try this.
var arr = [{"name":"aName","lastName":"aLastname"},{"name":"bName","lastName":"bLastname"}];
arr.forEach(function(d){
console.log(d.name, d.lastName);
});

javascript: get object item in real order [duplicate]

This question already has answers here:
Elements order in a "for (… in …)" loop
(10 answers)
Closed 8 years ago.
i need to get real order of simple javascript abject, but i get incorrect answer from this code:
var Obj={"x":"z", "2":"a", "1":"b"};
for(i in Obj)
document.write(Obj[i]+"<br>");
I expect to see z, a, b as answer, but i get b, a, z
See the code in action:
http://jsfiddle.net/gpP7m/
There's no guaranteed order in object keys iteration.
A for...in loop iterates over the properties of an object in an
arbitrary order
If you need one, use an array of key/value elements :
var obj=[
{key:"x", value:"z"},
{key:"2", value:"a"}
];
for (var i=0; i<obj.length; i++) document.write(obj[i].value+'<br>');
On a modern browser (not IE8), you can do :
document.write(obj.map(function(kv){ return kv.value }).join('<br>'));
(which doesn't do exactly the same but probably does what you want)
Check for below sample too
var data1 = {"x":"z", "2":"a", "1":"b"};
var arr = [];
var i=0;
$.each(data1,function(index,value) {
arr[i++] = value;
});
var len = arr.length-1;
while( len>=0 ) {
if( arr[len] !== undefined ) {
alert(arr[len]);
}
len--;
}
and referece link is Reverse object in jQuery.each
And fiddle update http://jsfiddle.net/gpP7m/3/

Categories