admin管理员组文章数量:1305654
what is the best way to convert an object of arrays to an array of objects and vice-versa
{
category : ['a','b','c'],
title : ['e','f','g'],
code : ['z','x','v']
}
To
[
{
category : 'a',
title : 'e',
code : 'z'
},
{
category : 'b',
title : 'f',
code : 'x'
},
{
category : 'c',
title : 'g',
code : 'v'
},
]
what is the best way to convert an object of arrays to an array of objects and vice-versa
{
category : ['a','b','c'],
title : ['e','f','g'],
code : ['z','x','v']
}
To
[
{
category : 'a',
title : 'e',
code : 'z'
},
{
category : 'b',
title : 'f',
code : 'x'
},
{
category : 'c',
title : 'g',
code : 'v'
},
]
Share
Improve this question
edited Feb 20, 2017 at 10:51
amir hosein ahmadi
asked Feb 20, 2017 at 10:49
amir hosein ahmadiamir hosein ahmadi
2621 silver badge12 bronze badges
3
-
Object.keys()
+Array.reduce()
– Shilly Commented Feb 20, 2017 at 10:51 - @amir, it is working for you ? – Mihai Alexandru-Ionut Commented Feb 20, 2017 at 11:29
- @amirhoseinahmadi, don't forget to accept an answer in order to help other people. – Mihai Alexandru-Ionut Commented Feb 20, 2017 at 13:38
4 Answers
Reset to default 6You could use two function for generating an array or an object. They works with
Object.keys
for getting all own property names,Array#reduce
for iterating an array and collecting items for return,Array#forEach
just fo itarating an array.
function getArray(object) {
return Object.keys(object).reduce(function (r, k) {
object[k].forEach(function (a, i) {
r[i] = r[i] || {};
r[i][k] = a;
});
return r;
}, []);
}
function getObject(array) {
return array.reduce(function (r, o, i) {
Object.keys(o).forEach(function (k) {
r[k] = r[k] || [];
r[k][i] = o[k];
});
return r;
}, {});
}
var data = { category: ['a', 'b', 'c'], title: ['e', 'f', 'g'], code: ['z', 'x', 'v'] };
console.log(getArray(data));
console.log(getObject(getArray(data)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use map()
and forEach()
var obj = {
category : ['a','b','c'],
title : ['e','f','g'],
code : ['z','x','v']
}
var result = Object.keys(obj).map(function(e, i) {
var o = {}
Object.keys(obj).forEach((a, j) => o[a] = obj[a][i])
return o
})
console.log(result)
Here is solution using reduce
method and arrow
function.
var obj={
category : ['a','b','c'],
title : ['e','f','g'],
code : ['z','x','v']
}
var result=obj[Object.keys(obj)[0]].reduce((a,b,i)=>{
var newObj={};
Object.keys(obj).forEach(function(item){
newObj[item]=obj[item][i];
});
return a.concat(newObj);
},[]);
console.log(result);
Not an answer to the original question, but thought I'd share this as I came here looking for a solution to a related problem: I needed the Cartesian product of values of uneven length. What I'm using for that:
/**
* Get the Cartesian product of a list of array args.
*/
const product = (...args) => args.length === 1
? args[0].map(x => [x])
: args.reduce(
(a, b) => Array.from(a).flatMap(
v1 => Array.from(b).map(v2 => [v1, v2].flat())
)
);
/**
* Map[String,Array[Any]] -> Array[Map[String,Any]]
*/
const arrayValuesToObjectArray = (obj) =>
product(...Object.values(obj)).map(values => Object.fromEntries(
Object.keys(obj).map((k, idx) => [k, values[idx]])
));
console.log(arrayValuesToObjectArray({
hello: ["this", "is", "a", "test"]
}));
console.log(arrayValuesToObjectArray({
one: ["foo"],
two: ["bar", "baz"],
three: ["this", "is", "three"],
}));
console.log(arrayValuesToObjectArray({
one: "foo",
two: "bar baz",
three: "this is three",
}));
本文标签: javascriptbest way to convert object with arrays to array with objects and viceversaStack Overflow
版权声明:本文标题:javascript - best way to convert object with arrays to array with objects and viceversa - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741798679a2398089.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论