有人可以帮助我转换此数组吗?
这是初始状态:
var arrOne = [
{
name: 'John',
phone: '111',
pass: '123'
},
{
name: 'Mike',
phone: '222',
pass: '456'
},
{
name: 'Steve',
phone: '333',
pass: '789'
},
];
我需要将其转换为:
var result = {
name: ['John', 'Mike', 'Steve'],
phone: ['111', '222', '333'],
pass: ['123', '456', '789']
}
答案 0 :(得分:2)
reduce
使这种转换变得简单;构建一个数组对象,并将对应的键推入其中:
var arrOne = [{name:'John',phone:'111',pass:'123'},{name:'Mike',phone:'222',pass:'456'},{name:'Steve',phone:'333',pass:'789'},];
const result = arrOne.reduce((a, e) => {
for (const k in e) {
if (!(k in a)) {
a[k] = [];
}
a[k].push(e[k]);
}
return a;
}, {});
console.log(result);
答案 1 :(得分:1)
以下解决方案采用数组中第一个对象的键,然后将这些键收集到最终对象中。因此,如果您向对象添加更多键,则无需更改任何内容。
var arrOne = [{name:'John',phone:'111',pass:'123'},{name:'Mike',phone:'222',pass:'456'},{name:'Steve',phone:'333',pass:'789'},];
console.log(
Object.keys(arrOne[0]).reduce(
(acc, key)=>({...acc, [key]: arrOne.reduce((acc,item)=>acc.concat(item[key]),[])})
, {})
)
答案 2 :(得分:0)
首先创建将保存结果的对象,然后遍历数组以绑定结果
var result = {
name: [],
phone: [],
pass: []
}
arrOne.map(u => {
result.name.push(u.name);
result.phone.push(u.phone);
result.pass.push(u.pass);
})
答案 3 :(得分:0)
reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。
您可以通过以下方式使用reduce()
:
var arrOne = [
{
name: 'John',
phone: '111',
pass: '123'
},
{
name: 'Mike',
phone: '222',
pass: '456'
},
{
name: 'Steve',
phone: '333',
pass: '789'
},
];
var result = arrOne.reduce((a,c) => {
for (var k in c) {
a[k] = a[k] || [];
a[k].push(c[k]);
}
return a;;
},{});
console.log(result);
答案 4 :(得分:0)
您可以使用动态方法,将所有键映射到新对象,然后将这些对象连接到单个对象。
var array = [{ name: 'John', phone: '111', pass: '123' }, { name: 'Mike', phone: '222', pass: '456' }, { name: 'Steve', phone: '333', pass: '789' }],
result = array.reduce((r, o) =>
Object.assign(
...Object.entries(o).map(([k, v]) => ({ [k]: [...(r[k] || []), v] }))
), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 5 :(得分:0)
您可以这样做:
var arrOne = [
{
name: 'John',
phone: '111',
pass: '123'
},
{
name: 'Mike',
phone: '222',
pass: '456'
},
{
name: 'Steve',
phone: '333',
pass: '789'
},
];
/*
var result = {
name: ['John', 'Mike', 'Steve'],
phone: ['111', '222', '333'],
pass: ['123', '456', '789']
}
*/
var result = {};
var keys = Object.keys(arrOne[1]); //console.log(keys);
//init empty array for result
keys.forEach(current=>{
result[current] = [];
});
//add value to result
arrOne.forEach(current=>{
for (let i=0; i<keys.length; i++)
result[keys[i]].push(current[keys[i]]);
});
console.log(result);