Is there a way in javascript to iterate through every value of a specific key from an object that is part of an array of objects and then create a new item for each value using a different key? Please allow me to explain with code what I would like to accomplish here.
This is what I have:
const x = [{
name: 'name1',
value: ['value1', 'value2', 'value3']
}, {
name: 'name2',
value: ['value4', 'value5', 'value6']
}]
This should be the new result:
const y = [{
'name1': 'value1',
'name2': 'value4',
}, {
'name1': 'value2',
'name2': 'value5',
}, {
'name1': 'value3',
'name2': 'value6',
}]
Any help will be truly appreciated!
Here is what I've tried so far. (It works, but I'm pretty sure there is a simpler way).
const y = [];
const z = [];
const xLength = x.length
for (let i = 0; i < xLength; i ) {
x[i].value.forEach((item, index) => {
z[index] = z[index] || [];
z[index].push(x[i].name, item);
});
}
z.forEach((items, index) => {
const obj = {};
items.forEach((item, k) => {
if (k % 2) {
obj[items[k - 1]] = item;
} else {
obj[item] = null;
}
});
y.push(obj);
});
CodePudding user response:
I believe this should work:
//start with array to store the answer
let y = []
//Next iterate threw each object in your 'x' array passing in to the callback xObj which is each object in your x array
x.forEach((xObj)=> {
//store the name value just to make it easier to read
let name = xObj.name
//iterate through the values in each xObj, getting the 'value' and the index
xObj.value.forEach((value, index)=>{
//check if the y array has anything at the same index, if not create a blank object
if(!y[index]) y[index]= {}
//put in that object a key:value with the 'name' and 'value'
y[index][name] = value
})
})
