2017-04-08 133 views
-2

我有一个数组对象,如下所述;如何迭代数组中的对象?

var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}]; 

我想日期格式的值提取到一个单独的数组,例如:

var dateArray=["apr1","apr2","apr3"]; 
var score=[1,2,3]; 

我使用的是for循环提取指标,但我没能得到的值。

+1

* “但我没能得到的值” * ...我们展示的代码。 Stackoverflow不是一个免费的代码编写服务,它的想法是帮助你修复你的代码**,但不能按预期执行 – charlietfl

回答

0

如果您只是不想对变量进行硬编码,则可以使用Array#forEachObject.keys将每个唯一键值存储在例如阵列。

注意:没关系许多钥匙你怎么在你的对象,下面的解决方案总是会把你返回正确的输出。请注意,您甚至不必首先声明新的变量。

var myArray = [{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}], 
 
    obj = {}; 
 
    
 
    myArray.forEach(v => Object.keys(v).forEach(function(c) { 
 
     (obj[c] || (obj[c] = [])).push(v[c]); 
 
    })); 
 
    
 
    console.log(obj);

0

创建空阵列,以及使用的forEach与“元素”(其代表阵列中的每个对象),并且每个的性质的推埃施的参数对象成所需的阵列。

var dateArray=[]; 
 
var score=[]; 
 
    
 
var myArray=[ 
 
    {dateformat:"apr1", score:1}, 
 
    {dateformat:"apr2",score:2}, 
 
    {dateformat:"apr3",score:3} 
 
]; 
 
    
 

 
myArray.forEach(function(element) { 
 
    dateArray.push(element.dateformat); 
 
    score.push(element.score); 
 
}); 
 

 
console.log(dateArray); //gives ["apr1","apr2","apr3"] 
 
console.log(score); //gives ["1","2","3"]

0

这里的答案是一个简单的循环。

var dateArray = new Array(myArray.length); 
for(var i = 0; i < myArray.length; ++i) { 
     var value = myArray[i]; 
     var dateValue = value.dateformat; 
     dateArray[i] = dateValue; 
} 

您可以使用map函数完成相同的:

var dateArray = myArray.map(function(value) { return value.dateformat; }); 
1

使用map遍历初始数组对象,并返回所需的项目。

var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}]; 
 

 
var dateArray = myArray.map(function(obj){return obj.dateformat;}), 
 
    score = myArray.map(function(obj){return obj.score}); 
 
    
 
console.log(dateArray); 
 
console.log(score);

0

您可以使用给定数组的单循环方式和重复键和推值到想要的阵列。

var myArray = [{ dateformat: "apr1", score: 1 }, { dateformat: "apr2", score: 2 }, { dateformat: "apr3", score: 3 }], 
 
    dateArray = [], 
 
    score = []; 
 

 
myArray.forEach(function (target, keys) { 
 
    return function(a) { 
 
     keys.forEach(function(k, i) { 
 
      target[i].push(a[k]); 
 
     }); 
 
    }; 
 
}([dateArray, score], ['dateformat', 'score'])); 
 

 
console.log(dateArray); 
 
console.log(score);

+0

为什么使用'reduce'?您的step函数使用累加器'r'并返回它,即所有步骤都使用相同的累加器(它是循环内的常量)。为什么不使用'forEach'呢? – melpomene

+0

@melpomene,对,只是把它改为闭包。 –