所以这里有我做的功能。我想提取数组中的names
和各个团队的runs
,以便我可以将它们用作响应,以便在图表中显示它们。
function unpack(obj, key) {
Object.keys(obj).forEach(function(key) {
var collection = [];
var collections = [];
for (var k in obj) {
collection.push(obj[k]);
}
console.log(collection);
return collection;
});
}
这是对象列表
[
{
name: "Scotland",
stats: {
runs: 16135,
wickets_taken: 1,
matches_played: 354
}
},
{
name: "Pakistan",
stats: {
runs: 70900,
wickets_taken: 43,
matches_played: 1066
}
},
{
name: "West Indies",
stats: {
runs: 61300,
wickets_taken: 280,
matches_played: 739
}
},
{
name: "Sri Lanka",
stats: {
runs: 108242,
wickets_taken: 741,
matches_played: 1049
}
}]
答案 0 :(得分:0)
让你的对象存储的变量是obj
function getData() {
var names = [];
var runs = [];
obj.forEach(function(item) {
names.push(item.name);
runs.push(item.stats.runs);
});
return {
runs: runs,
names: names,
}
}
//access them outside as:
var data = getData();
var names = data.names; //accessing name and run array returned from fxn
var runs = data.runs;
答案 1 :(得分:0)
您只需使用for循环
即可
var dataObj = [
{
name: "Scotland",
stats: {
runs: 16135,
wickets_taken: 1,
matches_played: 354
}
},
{
name: "Pakistan",
stats: {
runs: 70900,
wickets_taken: 43,
matches_played: 1066
}
},
{
name: "West Indies",
stats: {
runs: 61300,
wickets_taken: 280,
matches_played: 739
}
},
{
name: "Sri Lanka",
stats: {
runs: 108242,
wickets_taken: 741,
matches_played: 1049
}
}
];
var names = [];
var runs = [];
for(var i= 0; i< dataObj.length; i++)
{
names.push(dataObj[i].name);
runs.push(dataObj[i].stats.runs);
}
console.log('NAMES', names);
console.log('RUNS',runs);
&#13;