遍歷 JavaScript 中的物件鍵,從而處理其中的鍵值
比如:我們有一個這樣物件陣列 −
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];我們需要編寫一個 JavaScript 函式,該函式接收這樣的陣列,並在控制檯中輸出如下結果。
const output = [
{
col1: "b",
col2: "d"
},
{
col1: "f",
col2: "h"
}
];基本上,我們想要將物件鍵值(最初是一個數組)轉換為一個單值,該值將是物件鍵陣列的第二個元素。
它的程式碼如下 −
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];
const reduceArray = (arr = []) => {
const res = arr.reduce((s,a) => {
const obj = {};
Object.keys(a).map(function(c) {
obj[c] = a[c][1];
});
s.push(obj);
return s;
}, []);
return res;
};
console.log(reduceArray(arr));控制檯中的輸出結果如下 −
[ { col1: 'b', col2: 'd' }, { col1: 'f', col2: 'h' } ]
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP