0

I have two arrays

const time = ['00:00', '00:30', '01:00', '01:30']

const cost = [1.40, 5.00, 2.00, 3.00]

And I want to merge them into an array of objects with keys like so:

result = [
    {
        time: '00:00',
        cost: 1.40
    },
    {
        time: '00:30',
        cost: 5.00
    },
    {
        time: '01:00',
        cost: 2.00
    },
    {
        time: '01:30',
        cost: 3.00
    }
]
1
  • How do you think the array names will become property names? Commented Oct 4, 2020 at 10:51

4 Answers 4

4

You can try using Array.prototype.map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

const time = ['00:00', '00:30', '01:00', '01:30'];
const cost = [1.40, 5.00, 2.00, 3.00];
var result = time.map((t, i)=>({time: t, cost: cost[i]}));
console.log(result);

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

2 Comments

you can add .toFixed(2) to cost to display upto 2 digits after decimal. Nice way to use map.
@anandshukla, OP's output shows that he wants the cost in number not in string, thank you:)
0

It can be done by following way:-

const time = ['00:00', '00:30', '01:00', '01:30']
const cost = [1.40, 5.00, 2.00, 3.00]


let array = []
for(let i=0; i<4; i++){
  let obj = {}
  obj.time = time[i]
  obj.cost = cost[i]
  array.push(obj)
}
console.log(array)

output -

[
  { time: '00:00', cost: 1.4 },
  { time: '00:30', cost: 5 },
  { time: '01:00', cost: 2 },
  { time: '01:30', cost: 3 }
]

Comments

0

You can loop through one of the two arrays and then populate objects into a declarated array as below.

const time = ['00:00', '00:30', '01:00', '01:30'];
const cost = [1.4, 5.0, 2.0, 3.0];

let objArr = [];

time.forEach((t, i) => {
  objArr[i] = {
    time: t,
    cost: cost[i],
  };
});

console.log(objArr);

Comments

0

            const time = ['00:00', '00:30', '01:00', '01:30'];
            const nums = [1.99, 5.11, 2.99, 3.45 ];
            const newArray = [];


            time.forEach((element, index) => {
                newArray.push({
                    time: element,
                    cost: nums[index]
                })
            })

            console.log(newArray)
            

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.