[英]Loop through array of arrays which contain objects and get all specific values from the objects then show to the page JQuery
[英]loop through api data array to get values from objects
我有這樣的數據:
var data = [{one:1}, {two:2}, {three:3}]
我想遍歷此數據,並獲取鍵的值。 我正在尋找的結果是123。
我努力了:
var result = [];
for(i=0; i < data.length; i++){
result.push(data[i]);
}
但是,它所做的只是將對象推入變量數組“結果”中。
所以問題是,我如何獲得數據IE 1、2和3的值?
這樣就可以了。
var data = [{one:1}, {two:2}, {three:3}]
var result = [];
// read all items of data.
data.forEach(function(item) {
// read all keys of item.
Object.keys(item).forEach(function(key) {
result.push(item[key]);
});
});
或ES6
const data = [{one:1}, {two:2}, {three:3}]
let result = [];
data.forEach(item => {
result = [...result, ...Object.values(item)];
});
只需在某些瀏覽器(和nodejs 7)中添加它,就可以像這樣使用Object.values()
var data = [{one:1}, {two:2}, {three:3}]; var values = data.map(o=>Object.values(o)[0]); console.log(values);
如果您的數據結構不變,這意味着每個對象條目中只有一對鍵值對 ,請使用Array#map
遍歷條目,然后使用當前object
調用Object.keys
並使用[0]
獲取實際的鍵(例如, one
, two
, three
)並使用該鍵返回object
的值,然后您可以操縱需要result
:
const data = [{one:1}, {two:2}, {three:3}]; const result = data.map(object => object[Object.keys(object)[0]]); console.log(result); console.log(result.join(',')); console.log(result.join(''));
var data = [{one:1}, {two:2}, {three:3}]; var result = data.map(function (object) { return object[Object.keys(object)[0]] }); console.log(result); console.log(result.join(',')); console.log(result.join(''));
從對象獲取值,如下所示:
var result = [];
data.foreach((item) => {
item.keys().foreach( (key) => {
result.push(item[key]);
});
});
當數組中已經有數據時,您可以簡單地執行
var dataString = result.join('');
此函數將數組中的所有值合並為一個字符串,並使用給定的字符串作為分隔符。 傳遞空白字符串使其不使用分隔符。
或者,您可以執行以下操作:
var result = "";
data.foreach((item) => {
item.keys().foreach( (key) => {
result += item[key];
});
});
因為這將直接連接字符串。
如何使用reduce
, Object.values
和spread
?
const data = [{one:1}, {two:2}, {three:3}]
const flatMapValues = arr => {
return arr.reduce((collection, item)=> collection = [...collection, ...Object.values(item)], [])
}
這樣可以更好地擴展,因為它將所有值轉換為一個數組。
const data = [{one:1, four: 4}, {two:2, five:5}, {three:3, six: 6}]
const flatMapValues = arr => {
return arr
.reduce((collection, item)=> collection = [...collection, ...Object.values(item)], [])
.sort((a, b) => a > b)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.