Reputation: 1092
I have to implement new data in the form of a table into a legacy system. I just can't figure out how to merge the object values with the key and merge them into an array key
{
"amount": [
"33300.00",
"43075.00",
"93300.00",
"193300.00",
],
"rent_label": [
"Due",
"Due",
"Due",
"Due",
],
"date": [
"2020-04-02T00:00:00.000Z",
"2020-03-03T00:00:00.000Z",
"2020-02-04T00:00:00.000Z",
"2020-01-15T00:00:00.000Z",
]
}
What I already tried
let data = Object.keys(obj).map((key) => {
let keyVal = Object.values(obj[key]).map((val) {
return { [key]: val}
})
return data;
});
What I rather need is the array to be like this
[
{
"amount": "33300.00",
"rent_label": "Due",
"date": "2020-04-02T00:00:00.000Z"
},
{
"amount": "33300.00",
"rent_label": "Due",
"date": "2020-04-02T00:00:00.000Z"
},
{
"amount": "33300.00",
"rent_label": "Due",
"date": "2020-04-02T00:00:00.000Z"
},
]
Upvotes: 0
Views: 104
Reputation: 1849
const keys = Object.keys(obj);
const count = obj[keys[0]].length;
const array = [...Array(n).keys()].map(i => keys.reduce((acc, key) => ({...acc, [key]: obj[key][i]}), {}));
Upvotes: 1
Reputation: 5205
If the size of the array is different based on the key, you can do this:
const input = {
"amount": ["33300.00", "43075.00", "93300.00", "193300.00"],
"rent_label": ["Due", "Due", "Due", "Due", "TEST"],
"date": ["2020-04-02T00:00:00.000Z", "2020-03-03T00:00:00.000Z", "2020-02-04T00:00:00.000Z", "2020-01-15T00:00:00.000Z"]
}
function merge (data) {
const result = []
const keys = Object.keys(data)
const maxLength = Math.max(...keys.map(e => data[e].length))
for (let index = 0; index < maxLength; index++) {
result.push(keys.reduce((acc, value) => {
acc[value] = data[value][index] || null
return acc
}, {}))
}
return result
}
console.log(merge(input))
Upvotes: 1
Reputation: 286
like that:
const DATA_LENGTH = 4;
const DATA = {
"amount": ["33300.00","43075.00","93300.00","193300.00"],
"rent_label": ["Due","Due","Due","Due"],
"date": ["2020-04-02T00:00:00.000Z","2020-03-03T00:00:00.000Z","2020-02-04T00:00:00.000Z","2020-01-15T00:00:00.000Z"]
};
const newFormatData = [];
const dataKeys = Object.keys(DATA);
for (let i = 0; i < DATA_LENGTH; i++) {
const obj = {};
dataKeys.forEach(key => {
obj[key] = DATA[key][i];
});
newFormatData.push(obj);
}
'newFormatData' variable now holds the new format data.
Upvotes: 1
Reputation: 908
Assuming you know that all of the properties have the same length, this would probably do the trick:
let obj = {}; //Put your object here
let length = Object.keys(obj).length;
let outputArr = [];
for(let i = 0;i<length;i++){
outputArr = {};
}
Object.keys(obj).forEach(function(key) {
for(let i = 0;i<length;i++){
outputArr[i][key]=arr[key][i];
}
});
console.log(outputArr);
Upvotes: 1