0

I have two arrays:

let names1 = ["om","karan","ranjett","rocky"] <br>
let names2 = ["vaibhu","Shrushti","rekha","kunal"]

How do you iterate over both arrays and makes a new object. Get one element from names1 also from names2 and one random number and push these into an object

eg:-

obj = {

{

n1:"om" n2: "vaibhu" randomnumber:12 },

//remaining array

}

2
  • 1
    "I want a code", this isn;t a free coding service. Please see How to Ask. Show us your attempt Commented Jul 7, 2022 at 14:59
  • I believe you should consider the structure of your data. Iterating over 2 arrays considering they have the same length, would be risky. Commented Jul 7, 2022 at 15:15

1 Answer 1

1

Just map over it?

let names1 = ["om","karan","ranjett","rocky"]
let names2 = ["vaibhu","Shrushti","rekha","kunal"]

const combined = names1.map((item, index) => ({
  n1: item,
  n2: names2[index],
  randomnumber: Math.ceil(Math.random() * 100)
}));

console.log(combined);

/*
[
  { n1: 'om', n2: 'vaibhu', randomnumber: 49 },
  { n1: 'karan', n2: 'Shrushti', randomnumber: 87 },
  { n1: 'ranjett', n2: 'rekha', randomnumber: 1 },
  { n1: 'rocky', n2: 'kunal', randomnumber: 74 }
]
*/
Sign up to request clarification or add additional context in comments.

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.