[英]How does one, from an array of objects, collect and aggregate the merged variant of all objects with a specific equal property value?
[英]How does one retrieve all values from a specific named column from an array of table row like objects?
下面的變量引用了一個類似 object 結構的表。
const jstable = [{
"date": "2022-02-08",
"new_cases": "23100",
"deaths": "75",
"recovered": "30294"
}, {
"date": "2022-03-01",
"new_cases": "25854",
"deaths": "78",
"recovered": "25548"
}];
我需要將列date
的所有值存儲/推送到另一個數組中。 這是如何實現的?
您可以遍歷所有元素並獲得正確的屬性。
const jstable = [{"date":"2022-02-08","new_cases":"23100","deaths":"75","recovered":"30294"},{"date":"2022-03-01","new_cases":"25854","deaths":"78","recovered":"25548"}]; function col(array, column){ let result = []; for (let item of array) { result.push(item[column]); } return result; } console.log( col(jstable, 'date') );
.as-console-wrapper { min-height: 100%;important: top; 0; }
col(jstable, 'date')
會為您提供所有date
列值。
雖然您可以使用循環和收集器數組來執行此操作,但最簡潔的方法是使用map
:
let dates = jstable.map(row => row.date);
但是,如果您需要為多列創建 arrays, map
並不是最好的 function,因為它必須多次遍歷數組,對於您嘗試獲取的每一列一次。
JSON.parse(jstable).map(row => row.date);
這是你要找的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.