How to Convert JSON Object to JavaScript Array

How to convert JSON object to JavaScript array?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
result.push([i, json_data [i]]);

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

Converting JSON object into array of arrays in javascript

You can use Object.keys (which returns an array of all key of your json) in combination with array’s map to transform your json into a new array:

const boxes = Object.keys(obj).map(key => obj[key].box)

You can also use Object.values, which is actually nicer in your case:

const boxes = Object.values(obj).map(value => value.box)

How it works

Object.keys return an array:

Object.keys(obj) // ["1", "2", "3"]

then you can map over them to get the value of each item:

Object.keys(obj).map(key => obj[key]) // [{box: [...]}, {box: [...]}, {box: [...]}]

then in array.map's callback, you can simply only return the box value:

Object.keys(obj).map(key => obj[key].box) // [[...], [...], [...]]

Without Object.keys()

function getBoxes (object) {
var boxes = [];
for (var key in object) {
if (!object.hasOwnProperty(key)) continue;
boxes.push(object[key].box);
}
return boxes;
}

console.log(getBoxes(obj))

for...in can loop through object's properties, but it'll also loop over inherited properties, therefore we need to guard the loop with object.hasOwnProperty(key).


Object.keys(): Return an array of all enumerable property names of an object

Object.values(): Return an array of all enumerable values of an object

array.map(): Return a new array with each item of the original array transformed in a given callback function

array.slice(): Return a shallow copy of the original array

Convert JSON object to array using javascript

You can do it like below (using .map and .unshift):-

var json = '[{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen":1,"Restaurant":1},{"Day":"Nov 07","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":1},{"Day":"Nov 08","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null},{"Day":"Nov 09","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 10","Saavor Kitchen":null,"Home Kitchen":3,"Restaurant":null},{"Day":"Nov 11","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":null},{"Day":"Nov 13","Saavor Kitchen":null,"Home Kitchen":4,"Restaurant":1},{"Day":"Nov 14","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":1},{"Day":"Nov 15","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Nov 16","Saavor Kitchen":null,"Home Kitchen":5,"Restaurant":null},{"Day":"Oct 30","Saavor Kitchen":null,"Home Kitchen":null,"Restaurant":2},{"Day":"Oct 31","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":3}]';
var columns = ['Day', 'Saavor Kitchen', 'Home Kitchen', 'Restaurant'];
var result = JSON.parse(json).map(function(obj) { return columns.map(function(key) { return obj[key]; });});result.unshift(columns);console.log(result);console.log(Object.keys($.parseJSON(json)[0]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to convert JSON to Array in Javascript

The syntax of your expected output is incorrect as you cant have object without key value pair.

you can have your output as

{
"data" : [ [ 1, "Alex", 20 ] ]
},
{
"data" : [[ 2, "Zara", 18 ] ,
[ 2, "Zara", 19 ] ]
}

here is the solution considering above output

var inputArr = [  {    "data" : [          {            "month" : 1,             "name" : "Alex",             "sum" : 20          }      ]    },  {    "data" : [          {            "month" : 2,             "name" : "Zara",             "sum" : 18          },          {            "month" : 2,            "name" : "Zara",            "sum" : 19          }      ]    }];
inputArr.forEach(function(item){ for (var i=0; i< item.data.length; i++){ var myArr = []; myArr.push(item.data[i].month); myArr.push(item.data[i].name); myArr.push(item.data[i].sum); item.data[i] = myArr; }})
console.log(JSON.stringify(inputArr));

Convert Json object to array in nodejs

Your data is insode Photos object, and then you push in an empty array.
So when you find from the array, you need to get it from the correct position.

Correct code:

(function test(id) {
let PhotoData = "{\"Photos\":[{\"id\":\"Photo1\", \"Type\": \"Color\", \"Shade\": \"Grey\"}, {\"id\": \"Photo2\", \"Type\": \"Color\", \"Shade\": \"Red\"}]}"
let photoArray = []; //photoArray
let getPhoto = JSON.parse(PhotoData); //Converting to JSON object
console.log(getPhoto);
photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
console.log(photoArray);
const foundPhoto = photoArray[0].Photos.find((photo) => photo.id == id);

console.log(foundPhoto );
})("Photo1");

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];data.push(feed);
console.log(data);


Related Topics



Leave a reply



Submit