0

What is the best way to convert scraped data array :

[ 'random product 1', 'random product 2', 'random product 3', 'random product 4'] [ '$99', '$99', '$99', '$99']


 into object 

{ name: 'random product 1', price: '$100', }{ name: 'random product 2', price: '$100', }{ name: 'random product 3', price: '$100', }


I've tried

var keys = [ 'name', 'price' ] const mainData = {} for (i = 0; i < 10; i++) { let keyIdx = 0; for (j = 0; j < 2; j++) { if (l < 2) { //bundle.name and bundle.price contains above mentioned array of name and price mainData[keys[j]] = bundle.name[l]; // keyIdx++; j++; mainData[keys[j]] = bundle.price[l]; } 


but it returns only one object { name: 'random product 3', price: '$99' }


1

1 Answer 1

2

If you have 2 arrays with the same length you can map through one of the arrays, and use i to link the name with the corresponding price.

 const names = ['random product 1', 'random product 2', 'random product 3', 'random product 4'] const prices = ['$99', '$99', '$99', '$99'] const result = names.map((name, i) => { return { name, price: prices[i] } }); console.log(result);

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

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.