var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
$('#output').append(item.id + ' ' + item.name + '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
console.log(item.id, item.name)
})
Answer from Diego ZoracKy on Stack Overflowvar data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
$('#output').append(item.id + ' ' + item.name + '<br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
var data = [{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}];
jQuery(data).each(function(i, item){
console.log(item.id, item.name)
})
Use json2.js and parse your array of json object. See the working code below,
var data = '[{"id":10,"name":"sinu"},{"id":20,"name":"shinto"}]';
var obj = JSON.parse(data);
var append= '';
$.each(obj, function(i, $val)
{
append+= $val.id + ',';
});
$('#ids').text(append);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<label id='ids'/>
getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i = 0, len = data.length; i < len; i++) {
console.log(data[i]);
}
});
Check your console to see the output (Chrome, Firefox/Firebug, IE).
jQuery also provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
Use the parseJSON method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
containers contain single node. So simply use
$.each(tainers, function (i, v) {
var tid = v.TID,
top = v.Top,
cat = v.Category,
date = v.Date,
icon = v.Icon,
clink = v.ContainerLink,
uid = v.UniqueID;
cont += '<a href="' + clink + '">' + uid + '</a> ';
$('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
});
The program shows how to read json and store data into textbox:
$(document).ready(function(){
$.getJSON("Test.json",function(data){
$.each(data,function(key,value){
alert(data[key].attrib1name);
alert(data[key].attrib2name);
$('input').val(data[key].enterpriseName);
activities=data[key].activities;
console.log(value);
});
});
});
Ignoring the calls to your local storage, i have made a simplified example you can use as guide:
// Create the JSON object and stringify
var item1 = {
item_id:332443,
item_rank:3.6,
item_type:["BMW","Camry","Ford"]
};
var item2 = {
item_id:354443,
item_rank:2.6,
item_type:["BMW","Camry","Ford","Tesla","GM","Chevrolet"]
};
var itemsRecords = {
items:[item1,item2]
};
var itemsRecordsJSON = JSON.stringify(itemsRecords);
// On document ready, parse the JSON string to object again
// and show their items on the console.
$(document).ready(function()
{
var records = JSON.parse(itemsRecordsJSON);
records.items.forEach(function(item)
{
//console.log(item);
$("#results").append(
"<b>Id=" + item.item_id +
" - Rank=" + item.item_rank +
" - Type=" + item.item_type.join(",") +
"</b><hr>"
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results">
</div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WDV321 Advanced Javascript - JSON</title>
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
crossorigin="anonymous"></script>
<script src="createJSONArray.js"></script>
<script>
$(document).ready(function(){
// get the objects from local storage
allRecords = localStorage.getItem("studentRecords");
// convert JSON Object to Javascript object
var records = JSON.parse(allRecords);
// add counter
i =0;
// add loop to read the objects
records.students.forEach(function(item)
{
var listAdd = "";
// create variable to exract the array
var courses = records.students[i].student_courses;
// add inner counter
var j=0;
$.each( courses, function( ){
listAdd = listAdd + "<li style = 'margin-left: 80px'>" + courses[j] + "</li>" ;
j++;
courses.join("<br/>")
});
$("body").append ("<div class='studentCard'>" + "<h3>Student ID:<span id='id'>" + records.students[i].student_id + "</span></h3>" + "<p>Student GPA:<span id='gpa'>"+ records.students[i].student_gpa +"</span></p>" + "<p>Student Courses: </p>" + "<ul id = 'classes'></ul>" + listAdd + "</p>" + "</div>" );
i++;
});
});
</script>
<style>
.studentCard {
width:200px;
box-sizing:border-box;
background-color:lightblue;
padding-left:5px;
padding-top:3px;
border:thin solid blue;
box-shadow: 2px 2px 2px grey;
margin: 5px;
}
.studentCard h3 {
margin:0px;
}
# sort {
margin-left: 10px;
}
</style>
</head>
<body>
<h3>Creating and consuming a JSON object</h3>
</html>
How about:
var dates = new Array();
var prices = new Array();
for (foo in data) {
dates.push(data[foo].poll_date);
prices.push(data[foo].prix);
}
jsFiddle example. Plus it uses plain JavaScript.
you should be able to do something like :
$.getJSON(url, null, function(data) {
$.each(data, function(i,item){
dates.push(item.poll_date);
prices.push(parseFloat(item.prix));
$("#testout").append("A:" + item.poll_date + " B:" + item.prix + "<br>");
});
});
You should grab the "client" property first which is an array. Once you grab it, then you can iterate over it as an array.
{ //object | obj
"client":[ //property (array) | obj.client
{ //object inside array | obj.client[0]
"ClientID":"0000000001",
"Name":"Valdez Gilberto JR", //property | obj.client[0].Name
"Phone":"(956)542-8148",
"MedActID":"10",
"Gender":"M",
"Division":"WP",
"Address":"1905 Illinois Ave N",
"Class":"",
"CityState":"Brownsville TX 78521-6732"
},
{
"ClientID":"0000000002",
"Name":"Salazar Olga F",
"Phone":"(956)546-3909",
"MedActID":"100",
"Gender":"F",
"Division":"MP",
"Address":"Route 8 Box 626 (San Pedro)",
"Class":"",
"CityState":"Brownsville TX 78520"
}
]
}
This code will iterate over the objects inside the "client" property, and alert the names.
var obj = JSON.parse(data);
var client = obj.client; //client prop is an array
for(var i = 0; i < client.length; i++){
alert(client[i].Name);
}
You are trying to iterate an object, but you can't do that. What you want is to iterate trough the array which is in your object, keyed by client
Try this:
for(var i = 0; i < obj.client.length; i++){
console.log(obj.client[i].Name)
}
I figured out the reason: You are stringyfying twice before storing it in localstorage
try {
localStorage["flexuralStrengthSamples"] = (JSON.stringify(t97Samples)); //Stringify only once, since localstorage values needs to be string
var parsedObject = JSON.parse(localStorage["flexuralStrengthSamples"]); // should give the original object.
console.log(parsedObject[0].Beam1.MaxLoad); // Since parsedObject is still string, this was failing. Now should work fine
} catch (err) {
alert(err.message);
}
See the working fiddle here: http://jsfiddle.net/sandenay/pnb88p4s/
You can parse JSON using JSON.parse().
Update
Here is a sample of your data from JSON.parse().
[{"Result":"Fail","Method":"T97E-v1","Beam1":{"BeamAge":"1","WidthUpper":1,"WidthCenter":1,"WidthLower":1,"WidthAverage":1,"DepthRight":1,"DepthCenter":1,"DepthLeft":1,"DepthAverage":1,"MaxLoad":1,"FS":18,"PSI":"18.00000","BreakOutside":"No"}}]
In order to get at your data, you need to use bracket-notation for arrays and dot-notation for objects. So, let data be equal to that JSON Array, then you can do data[0].Result, which is "Fail", or data[0].Beam1.MaxLoad, which is 1.
No, with eval is not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data);
For this use the lib https://github.com/douglascrockford/JSON-js
I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.
It seems there's something about jquery's $.each that changes the nature of the elements in the array.
I wanted to do the following:
$.getJSON('/ajax/get_messages.php', function(data) {
/* data:
[{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
{"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]
*/
console.log ("Data0Title: " + data[0].title);
// prints "Data0Title: Failure"
console.log ("Data0Type: " + data[0].type);
// prints "Data0Type: error"
console.log ("Data0Details: " + data[0].details);
// prints "Data0Details: Unsuccessful. Please try again"
/* Loop through data array and print messages to console */
});
To accomplish the loop, I first tried using a jquery $.each to loop through the data array. However, as the OP notes, this doesn't work right:
$.each(data, function(nextMsg) {
console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
// prints
// "undefined (undefined): undefined
// "undefined (undefined): undefined
});
This didn't exactly make sense since I am able to access the data[0] elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each block with a for loop:
var i=0;
for (i=0;i<data.length;i++){
console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
// prints
// "Failure (error): Unsuccessful. Please try again"
// "Information Message (info): A basic informational message - Please be aware"
}
So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each
Either change the structure of the JSON so that single components will also be wrapped in an array or adjust convertJson()
function convertJson(data) {
//...
$.each(jsondata.license, function(k, lic) {
var components = lic.component.length ? lic.component : [lic.component]; // <- this
$.each(components, function(i, comp) {
//...
});
});
//...
};
fiddle
You have some invalid Json for component element - one time it is a single object, other it is an array of objects. Also some of your code need correction. I have put it all together here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Licenses</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
var jsonData = {
"@name": "Reuters TV iOS",
"license": [{
"@name": "OpenSSL Combined License",
"component": [{
"name": "OpenSSL",
"url": "http://www.openssl.org/"
}],
"licensetext": "LICENSE ISSUES \r\n==============\r\n \r\nThe OpenSSL toolkit stays under a dual license, i.e. both the conditions of\r\nthe OpenSSL License and the original SSLeay license apply to the toolkit.\r\nSee below for the actual license texts. Actually both licenses are BSD-style\r\nOpen Source licenses. In case of any license issues related to OpenSSL\r\nplease contact openssl-core@openssl.org.\r\n OpenSSL License \r\n---------------\r\n \r\n==================================================================== Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved. Redistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions\r\nare met:\r\n Redistributions of source code must retain the above copyright\r\n notice, this list of conditions and the following disclaimer.\r\n Redistributions in binary form must reproduce the above copyright\r\n notice, this list of conditions and the following disclaimer in\r\n the documentation and/or other materials provided with the\r\n distribution. All advertising materials mentioning features or use of this\r\n software must display the following acknowledgment: \r\n \"This product includes software developed by the OpenSSL Project\r\n for use in the OpenSSL Toolkit. (http://www.openssl.org/)\" The names \"OpenSSL Toolkit\" and \"OpenSSL Project\" must not be used to\r\n endorse or promote products derived from this software without\r\n prior written permission. For written permission, please contact\r\n openssl-core@openssl.org. Products derived from this software may not be called \"OpenSSL\" nor may \"OpenSSL\" appear in their names without prior written permission of the OpenSSL Project. Redistributions of any form whatsoever must retain the following\r\n acknowledgment: \r\n \"This product includes software developed by the OpenSSL Project\r\n for use in the OpenSSL Toolkit (http://www.openssl.org/)\" \r\nTHIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT \"AS IS\" AND ANY\r\nEXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR\r\nITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\r\nSTRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\r\nOF THE POSSIBILITY OF SUCH DAMAGE. \r\n====================================================================\r\n \r\nThis product includes cryptographic software written by Eric Young\r\n(eay@cryptsoft.com). This product includes software written by Tim\r\nHudson (tjh@cryptsoft.com).\r\n Original SSLeay License \r\n -----------------------\r\n Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) \r\nAll rights reserved. \r\nThis package is an SSL implementation written\r\nby Eric Young (eay@cryptsoft.com). \r\nThe implementation was written so as to conform with Netscapes SSL.\r\n \r\nThis library is free for commercial and non-commercial use as long as\r\nthe following conditions are aheared to. The following conditions\r\napply to all code found in this distribution, be it the RC4, RSA,\r\nlhash, DES, etc., code; not just the SSL code. The SSL documentation\r\nincluded with this distribution is covered by the same copyright terms\r\nexcept that the holder is Tim Hudson (tjh@cryptsoft.com).\r\n\r\nCopyright remains Eric Young's, and as such any Copyright notices in\r\nthe code are not to be removed. \r\nIf this package is used in a product, Eric Young should be given attribution\r\nas the author of the parts of the library used. \r\nThis can be in the form of a textual message at program startup or\r\nin documentation (online or textual) provided with the package.\r\n Redistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions\r\nare met:\r\n Redistributions of source code must retain the copyright\r\n notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright\r\n notice, this list of conditions and the following disclaimer in the\r\n documentation and/or other materials provided with the distribution. All advertising materials mentioning features or use of this software\r\n must display the following acknowledgement: \r\n \"This product includes cryptographic software written by\r\n Eric Young (eay@cryptsoft.com)\" \r\n The word 'cryptographic' can be left out if the rouines from the library\r\n being used are not cryptographic related :-). If you include any Windows specific code (or a derivative thereof) from\r\n the apps directory (application code) you must include an acknowledgement:\r\n \"This product includes software written by Tim Hudson (tjh@cryptsoft.com)\"\r\n \r\nTHIS SOFTWARE IS PROVIDED BY ERIC YOUNG \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\r\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\r\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\r\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\r\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\r\nSUCH DAMAGE.\r\n \r\nThe licence and distribution terms for any publically available version or\r\nderivative of this code cannot be changed. i.e. this code cannot simply be\r\ncopied and put under another distribution licence\r\n[including the GNU Public Licence.]"
}, {
"@name": "SIL Open Font License 1.1",
"component": [{
"name": "Font-Awesome",
"url": "http://github.com/FortAwesome/Font-Awesome/"
}],
"licensetext": " SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide\r\ndevelopment of collaborative font projects, to support the font creation\r\nefforts of academic and linguistic communities, and to provide a free and\r\nopen framework in which fonts may be shared and improved in partnership\r\nwith others. The OFL allows the licensed fonts to be used, studied, modified and\r\nredistributed freely as long as they are not sold by themselves. The\r\nfonts, including any derivative works, can be bundled, embedded, \r\nredistributed and/or sold with any software provided that any reserved\r\nnames are not used by derivative works. The fonts and derivatives,\r\nhowever, cannot be released under any other type of license. The\r\nrequirement for fonts to remain under this license does not apply\r\nto any document created using the fonts or their derivatives. DEFINITIONS \"Font Software\" refers to the set of files released by the Copyright\r\nHolder(s) under this license and clearly marked as such. This may\r\ninclude source files, build scripts and documentation. \"Reserved Font Name\" refers to any names specified as such after the\r\ncopyright statement(s). \"Original Version\" refers to the collection of Font Software components as\r\ndistributed by the Copyright Holder(s). \"Modified Version\" refers to any derivative made by adding to, deleting,\r\nor substituting — in part or in whole — any of the components of the\r\nOriginal Version, by changing formats or by porting the Font Software to a\r\nnew environment. \"Author\" refers to any designer, engineer, programmer, technical\r\nwriter or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining\r\na copy of the Font Software, to use, study, copy, merge, embed, modify,\r\nredistribute, and sell modified and unmodified copies of the Font\r\nSoftware , subject to the following conditions: 1) Neither the Font Software nor any of its individual components,\r\nin Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled,\r\nredistributed and/or sold with any software , provided that each copy\r\ncontains the above copyright notice and this license. These can be\r\nincluded either as stand-alone text files, human-readable headers or\r\nin the appropriate machine-readable metadata fields within text or\r\nbinary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font\r\nName(s) unless explicit written permission is granted by the corresponding\r\nCopyright Holder. This restriction only applies to the primary font name as\r\npresented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font\r\nSoftware shall not be used to promote, endorse or advertise any\r\nModified Version, except to acknowledge the contribution(s) of the\r\nCopyright Holder(s) and the Author(s) or with their explicit written\r\npermission. 5) The Font Software, modified or unmodified, in part or in whole,\r\nmust be distributed entirely under this license, and must not be\r\ndistributed under any other license. The requirement for fonts to\r\nremain under this license does not apply to any document created\r\nusing the Font Software. TERMINATION This license becomes null and void if any of the above conditions are\r\nnot met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\r\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\r\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE\r\nCOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\r\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\r\nOTHER DEALINGS IN THE FONT SOFTWARE. "
}, {
"@name": "zlib License",
"component": [{
"name": "iCarousel",
"url": "http://github.com/nicklockwood/iCarousel/"
}, {
"name": "FXKeychain",
"url": "http://github.com/nicklockwood/FXKeychain/"
}, {
"name": "FXForms",
"url": "http://github.com/nicklockwood/FXForms/"
}],
"licensetext": " The zlib/libpng License Copyright (c) <year> <copyright holders> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution."
}],
"isProjectComplete": "true"
};
function convertJson(jsondata) {
var output = "<ul>";
$.each(jsondata.license, function(k, lic) {
output += '<li>';
$.each(lic.component, function(k, comp) {
output += "<b>Name: </b>" + comp.name + " <br /> <b>URL</b> : " + "<a href=' " + comp.url + " '>" + comp.url + "</a>" + " <br />";
});
output += "<b>License</b><br /><ul>" + "<div class='license'>" + lic.licensetext + "</div></ul><br />" + "</li>";
});
output += "</ul>";
$("#licenses").html(output);
};
$(document).ready( function() {
convertJson(jsonData);
});
</script>
</head>
<body>
<div id="licenses"></div>
</body>
</html>
This works perfectly
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var i=0;i<parsedJSON.length;i++) {
alert(parsedJSON[i].Id);
}
}
But this doens't
function myFunction(dataFromServer){
var parsedJSON = JSON.parse(dataFromServer.d);
for (var item in parsedJSON) {
alert(item.Id);
}
}
You can just access them as you would any object:
var id = item.Id;
if (item.IsGood) { ... }
If you wish to enumerate them to use somehow, have a look at this SO question.
You'll need a list of the properties, in order, since JavaScript object properties are unordered by definition.
With that, it's straightforward:
var props = [
"current_day", "open_val", "high_val", "low_val", "close_val"
];
var data = [
{
"current_day":"2011-08-01",
"open_val":136.65,
"high_val":136.96,
"low_val":134.15,
"close_val":134.15
},
{
"current_day":"2011-08-02",
"open_val":135.26,
"high_val":135.95,
"low_val":131.50,
"close_val":131.85
}
]
var arrays = data.map(
function (o) {
var array = [];
props.forEach(
function (prop)
{
array.push( o[prop] );
}
);
return array;
}
);
console.log(arrays);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or, for older browsers lacking map() and forEach():
var props = [
"current_day", "open_val", "high_val", "low_val", "close_val"
];
var data = [
{
"current_day":"2011-08-01",
"open_val":136.65,
"high_val":136.96,
"low_val":134.15,
"close_val":134.15
},
{
"current_day":"2011-08-02",
"open_val":135.26,
"high_val":135.95,
"low_val":131.50,
"close_val":131.85
}
]
var arrays = [];
for ( var i = 0; i < data.length; ++i )
{
var array = [];
for ( var j = 0; j < props.length; ++j )
{
array.push( data[i][props[j]] );
}
arrays.push(array);
}
console.log(arrays);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can try this
You need to map the array, so each new term is the value of each key of the contained object, so:
var stuff = [
{
"current_day":"2011-08-01",
"open_val":136.65,
"high_val":136.96,
"low_val":134.15,
"close_val":134.15
},
{
"current_day":"2011-08-02",
"open_val":135.26,
"high_val":135.95,
"low_val":131.50,
"close_val":131.85
}
];
var result = stuff.map(function (object) {
var arr = [];
for(var prop in object) {
arr.push(object[prop]);
}
return arr;
});
alert(result);