遍历 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