1

I have an array:

const array = [
  {name: "abc", numbers:[1,2]},
  {name: "def", numbers:[3,4]}
];

I want to use .map() to return a new array like:

[
  {name:"abc", number:1},
  {name:"abc", number:2},
  {name:"def", number:3},
  {name:"def", number:4}
]

What should I do?

1
  • do u want to return a copy of the array? Commented May 7, 2020 at 5:43

5 Answers 5

2

It would be more performant to use forEach instead of map.

As @MohammadUsman's nice answer shows, the output of map has to be flattened before you can get the result you want. With forEach (which returns nothing), you can just append to the output array directly:

const data = [
  { name: "abc", numbers: [1,2] },
  { name: "def", numbers: [3,4] }
];

var result = [];
              
data.forEach(
  ({ numbers, ...rest }) => numbers.forEach(
    n => result.push(Object.assign({number: n}, rest )))
);

console.log(result);

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

Comments

1

You can iterate over input array using .map() and use Object.assign() to generate new object and finally flat the array using .flat() to get the desired output.

const data = [
  { name: "abc", numbers: [1,2] },
  { name: "def", numbers: [3,4] }
];
              
const result = data.map(
  ({ numbers, ...rest }) => numbers.map(n => Object.assign({number: n}, rest ))
).flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

1

You could take directly Array#flatMap with an inner mapping of new objects and get an array of objects.

const
    array = [{ name: "abc", numbers:[1, 2] }, { name: "def", numbers:[3, 4] }],
    result = array.flatMap(({ name, numbers }) => numbers.map(number => ({ name, number })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use .reduce if flatmap not available. It is faster in your cases. Iteration will be only one time for each element.

const array = [
  { name: "abc", numbers: [1, 2] },
  { name: "def", numbers: [3, 4] },
];
const results = array.reduce((r, item) => {
  r = r.concat(item.numbers.map((number) => ({ name: item.name, number })));
  return r;
}, []);
console.log(results)

Comments

0

Here is a simple solution if you are up for using jquery...

const array = [
               {name: "abc", numbers:[1,2]},
               {name: "def", numbers:[3,4]}
              ];

var newArray = [];
$.each(array, function(k,v){
  var strName = v.name;
    $.each(v.numbers, function(key,value){
        newArray.push({name: strName, number: value});
  });
});


console.log(newArray);

Comments

Your Answer

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.