Js 怎么将 1 种数组转换为另一种数组?

2020-01-03 01:00:51 +08:00
 LionXen
请教大佬。

array[0][name]:apple
array[0][price]:55.00
array[0][tips]:red apple
array[1][name]:orange
array[1][price]:41.13
array[1][tips]:4orange

如何转换为:

array[name][0]:apple
array[name][1]:orange
array[price][0]:55.00
array[price][1]:41.13
array[tips][0]:red apple
array[tips][1]:4orange
2718 次点击
所在节点    JavaScript
9 条回复
Pastsong
2020-01-03 01:17:05 +08:00
这。。for-loop 不就好了
l1nyanm1ng
2020-01-03 09:28:35 +08:00
```js
const array = [
{
name: 'apple',
price: 55.0,
tips: 'red apple',
},
{
name: 'orange',
price: 41.13,
tips: '4 orange',
}
];

const ret = array.reduce((accmulator, current) => {
Object.entries(current).forEach(([prop, value]) => {
if (!Reflect.has(accmulator, prop)) {
accmulator[prop] = [];
}
accmulator[prop].push(value);
});
return accmulator;
}, {});

console.log(ret);
```
xiaoming1992
2020-01-03 09:47:56 +08:00
跟#2 差不多
``` javascript
const arr = [
{
name: "name1",
price: "price1",
tips: "tips1",
},
{
name: "name2",
price: "price2",
tips: "tips2",
},
]

const result = arr.reduce((prev, cur, i) => {
Object.entries(cur).forEach(([key, val]) => {
if (!prev[key]) { prev[key] = [...new Array(arr.length)] }
prev[key][i] = val
})
return prev
}, {})

console.log(result)
```
palmers
2020-01-03 10:48:45 +08:00
```js
const arr = [{name: 'apple', price: 55.00, tips: 'red apple'}, {name: 'org', price: 52.00, tips: 'red apple'}];
const vx = arr.reduce((ac, item) => {
const keys = Object.keys(item);
keys.map(key => {
const has = ac.hasOwnProperty(key);
if(has) {//{name: 'apple', price: 55.00, tips: 'red apple'}
const maybeArr = ac[key];
const isArr = Array.isArray(maybeArr);
if(isArr) { ac[key].push(item[key])}else {ac[key] = [ac[key], item[key]];}
}else {
ac[key] = [ac[key]];
}
});
return ac;
});
console.log(vx);
```
我这是比较笨拙的写法 😄 基本都是 reduce 来做
jianguiqubaa
2020-01-03 10:50:03 +08:00
arr.reduce((acc, item) => Object.entries(item).reduce((pre, [key, value]) => ({...pre, [key]: [...(pre[key] || []), value]}), acc), {})
palmers
2020-01-03 11:01:04 +08:00
@jianguiqubaa 完美 , 代码太帅了!!
kyuuseiryuu
2020-01-03 14:09:32 +08:00
const arr = [
....{
........name: "name1",
........price: "price1",
........tips: "tips1",
....},
....{
........name: "name2",
........price: "price2",
........tips: "tips2",
....},
]
console.log(arr);
const result = {};
arr.forEach(element => {
....Object.keys(element).forEach(key => {
........if (!result[key]) {
............result[key] = [];
........}
........result[key].push(element[key]);
....})
});

console.log(result);

为什么要用 reduce,foreach 不香吗?
onfuns
2020-01-03 17:04:44 +08:00
for 循环啊,非开源项目不要写的太精简,不然后期有维护的可能性,到时就蛋疼了。业务代码就要一目了然!
clare233
2020-01-03 23:49:44 +08:00
7 楼的优雅,业务代码确实不是写的越短约好,7 楼这个很一目了然

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/634620

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX