0

this is my array:

      {
          "dateOfBirth": 25
      },
      {
          "dateOfBirth": [
              {
                  "dateOfBirth": 27
              },
              {
                  "dateOfBirth": 35
              }
          ]
      }

i want to convert it like this:

[25, 27, 35]

i am using map function but how can i convert array of objects inside of it?

var finalArray = someJsonArray.map(function (obj) {
  return obj.dateOfBirth;
});
console.log(finalArray); 
//  output
[
        25,
        [
            {
                "dateOfBirth": 27
            },
            {
                "dateOfBirth": 35
            }
        ]
    ]
1
  • 3
    What have you tried so far (a second .map(), a recursive approach, ...) to solve this on your own? Commented Sep 6, 2021 at 12:05

3 Answers 3

3

A very simple one off solution would be:

const someJsonArray = [
  { "dateOfBirth": 25 },
  { "dateOfBirth": [
    { "dateOfBirth": 27 },
    { "dateOfBirth": 35 },
    { "dateOfBirth": [
      { "dateOfBirth": 42 },
    ]}
  ]}
];

const out = someJsonArray.flatMap(function r(el) {
  return Array.isArray(el.dateOfBirth) //  ^----------------\
    ? el.dateOfBirth.flatMap(r)        // << recursion with r()
    : el.dateOfBirth;
});

console.log(out);

Ref:

Sign up to request clarification or add additional context in comments.

Comments

1

One way of doing this is by using a recursive approach, and returning any property that matches the one you're looking for (in this case 'dateOfBirth'). You'd create a function like getPropertyValues and recurse through your object / array to return the array of desired values.

const input = [{ "dateOfBirth": 25 }, { "dateOfBirth": [ { "dateOfBirth": 27 }, { "dateOfBirth": 35 } ] }];

function getPropertyValues(obj, property) {
    const output = [];
    for(let prop in obj) {
        if (typeof(obj[prop]) === 'object') {
            output.push(...getPropertyValues(obj[prop], property));
        } else if (prop === property) { 
            output.push(obj[prop]); 
        }
    }
    return output;
}

console.log('Property values:', getPropertyValues(input, 'dateOfBirth'))

Comments

1

Use a recursive function with Array.map to make it dynamic

const data = [
  { "dateOfBirth": 25 },
  {
    "dateOfBirth": [
      { "dateOfBirth": 27 },
      { "dateOfBirth": 35 },
      {
        "dateOfBirth": [
          { "dateOfBirth": 40 },
          { "dateOfBirth": 41 }
        ]
      }
    ]
  }
];
const output = data.reduce((acc, curr) => myReducer(acc, curr), []);

function myReducer(acc, curr) {
  if(typeof curr.dateOfBirth === "number") {
    // Its a number
    acc.push(curr.dateOfBirth)
  } else {
    // Its an array
    for (let index in curr.dateOfBirth) {
      myReducer(acc, curr.dateOfBirth[index])
    }
  }
  return acc;
}
console.log(output);

Comments

Your Answer

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