I just want to return an array containing the first and second objects of the element.
The next 2 elements will be repeated after traversing the keys
Given the following object:
const object = {
a: [
{ name: "John", age: 32 },
{ name: "David", age: 23 },
{ name: "Justin", age: 28 },
{ name: "Arnauld", age: 35 }
],
b: [
{ name: "Ivan", age: 18 },
{ name: "Nekko", age: 13 },
{ name: "Lena", age: 25 }
],
c: [
{ name: "Ann", age: 19 },
{ name: "Nick", age: 14 }
]
};
the result I want is
[
{ name: "John", age: 32 },
{ name: "David", age: 23 },
{ name: "Ivan", age: 18 },
{ name: "Nekko", age: 13 },
{ name: "Ann", age: 19 },
{ name: "Nick", age: 14 },
{ name: "Justin", age: 28 },
{ name: "Arnauld", age: 35 },
{ name: "Lena", age: 25 }
]
CodePudding user response:
You can use Object.values() and then you can use array.reduce() to get desire values.
const object = {
a: [
{ name: "John", age: 32 },
{ name: "David", age: 23 },
{ name: "Justin", age: 28 },
{ name: "Arnauld", age: 35 }
],
b: [
{ name: "Ivan", age: 18 },
{ name: "Nekko", age: 13 },
{ name: "Lena", age: 25 }
],
c: [
{ name: "Ann", age: 19 },
{ name: "Nick", age: 14 }
]
};
let newArray = Object.values(object).reduce((prev, current) => ([...prev, ...current.slice(0,2)]),[]);
console.log(newArray)
CodePudding user response:
const object = {
a: [
{ name: "John", age: 32 },
{ name: "David", age: 23 },
{ name: "Justin", age: 28 },
{ name: "Arnauld", age: 35 }
],
b: [
{ name: "Ivan", age: 18 },
{ name: "Nekko", age: 13 },
{ name: "Lena", age: 25 }
],
c: [
{ name: "Ann", age: 19 },
{ name: "Nick", age: 14 }
]
};
const result = Object.values(object).reduce((acc, cur) => {
const arr = cur.map((item, index) => {
return { ...item, index: Math.floor(index / 2) };
});
return [...acc, ...arr];
}, []).sort((a,b) => a.index - b.index);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
this gives exact the order as you requested it.
EDIT
Explanation:
The solution iterates over Object.values()
array and uses .reduce()
in order to first assign an index
to each element (in the arrays corresponding to keys a
, b
, c
.
Then, it uses .sort()
to obtain the desired order in the resulting array.
CodePudding user response:
const names = [];
while (true) {
let test = false;
for (const [key, value] of Object.entries(object)) {
if (value.length > 0) {
const arrays = value.splice(0, 2)
names.push(...arrays)
test = true
}
}
if (test === false) break;
}
console.log(names);
i think something like this will do, but be careful using splice because it'll delete the values from the array