0

How to zip any number of arrays, which are properties of an object, in a specific format in javascript to get the following outcome?

This is the original object.

const items = {
distance: [1,5,12, ...],
time: [10,20,30,..],
...
}

expected outcome :

const result = [
{distance: 1, time: 10},
{distance: 5, time: 20},
{distance: 12, time: 30},
...
]

I tried with loadash zip and vanilla js mapping and all. It is not working!

This is a sample of what I have tried:

But not working!

zip(
  Object.entries(items ).map(
    ([key, values]) =>
      values.map((val, index) => ({
        [key]: val[index],
      }))
  )
)) 

3 Answers 3

1

With plain Javascript, you could reduce the entries and map objects.

const items = { distance: [1, 5, 12], time: [10, 20, 30] },
result = Object
    .entries(items)
    .reduce((r, [k, a]) => a.map((v, i) => ({ ...r[i], [k]: v })), []);

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

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

Comments

0

Quite easy with lodsah _.zipWith:

const items = {
    distance: [1,5,12],
    time: [10,20,30]
}


const result = _.zipWith(
      items.distance, 
      items.time, 
      (distance,time) => ({distance,time})
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Comments

0

With vanilla JavaScript, you can use Object.fromEntries, Object.entries, map,... to create the result array:

const zipObject = obj => Object.values(obj)[0].map((_, i) =>
    Object.fromEntries(
        Object.entries(obj).map(([key, val]) => [key, val[i]])
    )
);

// Demo
const items = {
  distance: [1,5,12],
  time: [10,20,30],
};

console.log(zipObject(items));

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.