I try to doing this object
obj={
a:{ 1:"x", 2:"c"},
b:{ 1:"v", 2:"b" },
c:{ 4:"n", 2:"k" }
}
to
obj=[
0:{group:"a" ,1:"x"},
1:{group:"a", 2:"c"},
2:{group:"b",1:"v"},
3:...]
You can use Object.entries() to convert the object into an array. Use .reduce(), .concat() and map() to construct the new array
let obj = {
a: {
1: "x",
2: "c"
},
b: {
1: "v",
2: "b"
},
c: {
4: "n",
2: "k"
}
}
let result = Object.entries(obj)
.reduce((c, [k, v]) => c.concat(Object.entries(v).map(o => ({group: k,[o[0]]: o[1]}))), [])
console.log(result);
Use Object.keys to get all the keys from the object. Then use array reduce function & inside the callback function loop over the object and create a new object.
let obj = {
a: {
1: "x",
2: "c"
},
b: {
1: "v",
2: "b"
},
c: {
4: "n",
2: "k"
}
}
let m = Object.keys(obj);
let z = m.reduce(function(acc, curr) {
if (typeof(obj[curr]) === 'object') {
for (let keys in obj[curr]) {
let __ob = {};
__ob.group = curr;
__ob[keys] = obj[curr][keys]
acc.push(__ob)
}
}
return acc;
}, [])
console.log(z)
You can iterate over your keys at both levels and use computed keys syntax as provided by ES6/ES2015:
let obj={ a:{ 1:"x", 2:"c"}, b:{ 1:"v", 2:"b" }, c:{ 4:"n", 2:"k" } }
let result = []
for (let k1 in obj){
for (let k2 in obj[k1] ){
result.push({group:k1,[k2]:obj[k1][k2]})
}
}
console.log(result)
Using lodash, iterate the the object with _.flatMap(). In the flatMap's callback, the 1st parameter is the value ({ 1: 'x', 2: 'c' } for example), and the 2nd parameter is the key (a for example). Assign the 2nd parameter to group. Use _.toPairs() to get an array of pairs ([key, value]). Convert the pairs to object with Array.map(), and include the group:
const obj = {"a":{"1":"x","2":"c"},"b":{"1":"v","2":"b"},"c":{"2":"k","4":"n"}};
const result = _.flatMap(obj,
(o, group) =>
_.toPairs(o).map(([k, v]) => ({
group,
[v]: k
})));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
toobject is confusing. You suggest you want an array, but that is not the proper syntax. It uses square brackets like an array, but key/val pairs like an object. One suggestion may be to be more explicit/correct in what your desired value will be