2017-09-13 54 views
-6

我有这样一组数据使用地图至jsx打印对象的属性?

const data = [{ 
    date: '2017-1-1', 
    abc: 1, 
    def: 2 
},{ 
    date: '2017-1-2', 
    abc: 3, 
    def: 6 
}] 

的如何打印

on date of 2017-1-1 
abc is equal to 1 and def is equal to 2 

on date of 2017-1-2 
abc is equal to 3 and def is equal to 6 

我卡在得到ABC和DEF财产出去JSX。如果我做data.map(o => o.abc),我可以得到1,但是如何使用map获取属性?或者我应该使用Object.keys和forEach?

我不能硬编码abc或def coz它可能有其他新属性。

回答

-1

使用模板文字。是这样的:

data.map(o => `on date of ${o.date} abc is equal to ${o.abc} and def is equal to ${o.def}`) 
+0

笑ABC和DEF硬编码 –

-1

使用forEach而不是地图,因为你不感兴趣的获得新的阵列

尝试以下解决方案

const data = [{ 
 
    date: '2017-1-1', 
 
    abc: 1, 
 
    def: 2 
 
},{ 
 
    date: '2017-1-2', 
 
    abc: 3, 
 
    def: 6 
 
}]; 
 

 
data.forEach(function(item){ 
 
    var output = []; 
 
    Object.keys(item).forEach(function(key) { 
 
    if(key !== "date") 
 
     output.push(key +" is equal to "+item[key]); 
 
}); 
 

 
console.log("on date of "+item.date+" "+ output.join(" and ")); 
 
})

+0

不能硬编码abc和def属性 –

+0

@Debabrata @Debabrata,请再读一遍,因为我提到我不需要数组,因此我不想使用地图 – Nemani

+0

@CeciliaChan,我已经更新了解决方案,对于动态键值对 – Nemani