使用此JSON对象:
{
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
}
我如何循环使用并将每对日期价格保存在一个简单的数组中,使用类似的东西,例如:
var transformation = [];
transformation.push({date: i, price: d})
因为这里的问题是在控制台中,当我打印JSON对象时,它说它们是数组内的对象,所以我不能使用forEach()
循环
答案 0 :(得分:2)
假设您已将JSON解析为对象......
var obj = JSON.parse(json);
... map
数据。
注意:根据您对我的问题的回答,您需要一个嵌套的数组结构,而不是一个对象数组(正如您在问题中所要求的那样)。
ES5
var transformation = obj.date_price.map(function(el) {
return [ el.date, el.price ];
});
ES6
var transformation = obj.date_price.map(el => [ el.date, el.price ]);
输出
[
["Jan 2000", 1394.46],
["Feb 2000", 1366.42],
["Mar 2000", 1498.58],
["Apr 2000", 1452.43]
]
答案 1 :(得分:1)
编辑:因为您已经将JSON作为对象,所以您只需要从中获取date_price属性。这是一个完全符合您需要的对象类型的数组......所以......
create table parties (
party_id int primary key,
type text not null check (...),
individual_name text null,
organization_name text null,
check ( /* validate columns for given types */ )
);
create table shareholders (
shareholder_party_id int references parties(party_id),
organization_party_id int references parties(party_id),
share decimal(...) not null,
primary key (shareholder_party_id, organization_party_id),
check (...)
);
insert into table parties values
(1, 'Individual', 'Alice', null),
(2, 'Individual', 'Bob', null)
(3, 'Organization', null, 'Alice and Bob Co.');
insert into shareholders values
(1, 3, 0.5), --Alice owns 50% of Alice and Bob Co.
(2, 3, 0.5); --Bob owns 50% of Alice and Bob Co.
insert into assets (asset_id, owner_id) values (1, 3); --Alice and Bob Co own Asset 1
或者...
var result = jsonObject.date_price; // THIS is your array here.
先前给出的答案,假设是JSON字符串......
只需使用此...
var result = jsonObject['date_price']; // THIS is your array here.
答案 2 :(得分:1)
使用dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.parse:parse-android:1.+'
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.android.support:design:23.2.0'
compile 'com.android.support:support-v4:23.2.0'
}
和JSON.parse
函数的简单解决方案:
Array.map

答案 3 :(得分:0)
您可以这样做:
var abc = {
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
}
var array = $.map(abc, function(value, index) {
return [value];
});
答案 4 :(得分:0)
最简单的解决方案。它已经是您需要的格式。您只需要删除嵌套。
var obj = {
"date_price": [
{
"date": "Jan 2000",
"price": 1394.46
},
{
"date": "Feb 2000",
"price": 1366.42
},
{
"date": "Mar 2000",
"price": 1498.58
},
{
"date": "Apr 2000",
"price": 1452.43
}
]
};
var array = obj['date_price'];
就是这样。