[英]React - How to convert a nested object into a array
I have the following object that I would like to convert it into an array of object and each object from the array to have the key: value[0].我有以下 object,我想将其转换为 object 的数组,并且数组中的每个 object 都有键:value[0]。
object: object:
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
output output
const arr = [
{comedy: 'book1'},
{comedy: 'book2'},
{action: 'book3'},
{action: 'book4'},
{drama: 'book5'},
]
So far I have tried solving this with loops and using Object.entries
.到目前为止,我已经尝试通过循环和使用Object.entries
来解决这个问题。 But I do not get the output I need.但我没有得到我需要的 output。
let result = [];
for(const [key1, value1] of Object.entries(arr)) {
for (const [key2, value2] of Object.entries(value1)) {
if(result[key2]) {
result[key2] [key1] = value2
} else {
result[key2] = {[key1]: value2}
}
}
}
console.log(result)
I have also tried to loop recalling the function inside itself.我还尝试循环调用 function 内部。 (I have found this search for the answer). (我找到了这个寻找答案的方法)。 But it will get stucked in a infinite loop.但它会陷入无限循环。
const result = [];
const getArray = (obj) => {
if (!obj) return;
const {keys, ...rest} = obj;
result.push({...rest});
getArray(keys);
}
console.log('here', getArray(arr));
const obj = { comedy: ['book1', 'book2'], action: ['book3', 'book4'], drama: ['book5'], } const result = Object.keys(obj).reduce((acc, key) => [...acc, ...obj[key].map((value) => ({[key]: value}))], [] ) console.log(result)
Try this尝试这个
function nestedObjectIntoArray(obj) {
const arr = [];
for (const key in obj) {
for (const value of obj[key]) {
const obj = {};
obj[key] = value;
arr.push(obj);
}
}
return arr;
}
const obj = {
comedy: ["book1", "book2"],
action: ["book3", "book4"],
drama: ["book5"],
};
console.log(nestedObjectIntoArray(obj));
You could use a reduce over the entries of obj
, adding objects to the accumulator for each entry in the array value:您可以对obj
的条目使用 reduce,为数组值中的每个条目将对象添加到累加器:
const obj = { comedy: ['book1', 'book2'], action: ['book3', 'book4'], drama: ['book5'], } const arr = Object.entries(obj).reduce((acc, [k, v]) => acc.concat(v.map(b => ({ [k]: b }))), [] ) console.log(arr)
const obj = { comedy: ['book1', 'book2'], action: ['book3', 'book4'], drama: ['book5'], } let result = Object.entries(obj).flatMap(([k,v]) => v.map(n => ({[k]:n})) ) console.log(result)
We can also achieve this by just using Array.forEach()
method.我们也可以通过使用Array.forEach()
方法来实现这一点。
Live Demo :现场演示:
// Input object const obj = { comedy: ['book1', 'book2'], action: ['book3', 'book4'], drama: ['book5'], }; // Declare a variable to store the final result. const arr = []; // Iterate the input object based on the keys and build the final object. Object.keys(obj).forEach(key => { obj[key].forEach(item => { arr.push({ [key]: item }) }) }); // Result console.log(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.