0

I have a problem on combining arrays that I wanted to get that's coming from another array.

datas

 datas = [
 {
 "id": "22333",
 "name": "",
 "details": [
 {
 "value": 1
 },
 {
 "value": 2
 }
 ]
 },
 {
 "id": "4444",
 "name": "",
 "details": [
 {
 "value": 99
 },
 {
 "value": 66
 }
 ]
 }
 ]

expected output

final = [
 {
 "value": 1
 },
 {
 "value": 2
 },
 {
 "value": 99
 },
 {
 "value": 66
 }
 ]

Code

 datas.map((data) => ({ ...data.details}))
asked Nov 15, 2021 at 1:41
0

3 Answers 3

4

Replace map with flatMap.

The flatMap method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map followed by a flat of depth 1, but slightly more efficient than calling those two methods separately.

const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}];
 
const flattened = datas.flatMap(obj => obj.details);
console.log(flattened);

To get the actual numbers map over the details array.

const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}];
 
const flattened = datas.flatMap(obj => {
 return obj.details.map(el => el.value);
});
console.log(flattened);

answered Nov 15, 2021 at 1:46
Sign up to request clarification or add additional context in comments.

2 Comments

How about getting the value only? Like [2, 99, 66]. I did const flattened = datas.flatMap(obj => obj.details.value); but it got undefined.
See the updated answer @Joseph
1
datas.reduce((acc, val) => {
 return acc.concat(val.details)
}, [])
answered Nov 15, 2021 at 1:46

Comments

0

You can also make use of reduce here:

arr.reduce((acc, curr) => {
 acc.push(...curr.details);
 return acc;
}, [])

const arr = (datas = [
 {
 id: "22333",
 name: "",
 details: [
 {
 value: 1,
 },
 {
 value: 2,
 },
 ],
 },
 {
 id: "4444",
 name: "",
 details: [
 {
 value: 99,
 },
 {
 value: 66,
 },
 ],
 },
]);
const result = arr.reduce((acc, curr) => {
 acc.push(...curr.details);
 return acc;
}, []);
console.log(result);

answered Nov 15, 2021 at 2:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.