Создание из 2 массивов массив объектов
Здравствуйте, Всем!
Помогите, пожалуйста разобраться. Обыскался уже... Есть задача объединить два массива в объект массивов. var positions = [ 'Bosh VZHIH-101', 'Ariston WHO-D', 'Atlant Mattel 2016', 'Wirpool FLASH black edition', 'Bosh VH1Z-024' ]; var prices = [ 10000, 4800, 9200, 2500, 5700 ]; На выходе нужно получить: [ { name: 'Bosh VZHIH-101', price:10000}, { name: 'Ariston WHO-D', price:4800}, { name: 'Atlant Mattel 2016', price:9200 }, { name: 'Wirpool FLASH black edition', price:9200 }, { name: 'Bosh VH1Z-024', price:5700} ] У меня же получается: [ { name: 'Bosh VZHIH-101' }, { name: 'Ariston WHO-D' }, { name: 'Atlant Mattel 2016' }, { name: 'Wirpool FLASH black edition' }, { name: 'Bosh VH1Z-024' }, { price: 10000 }, { price: 4800 }, { price: 9200 }, { price: 2500 }, { price: 5700 } ] Мой код: 'use strict'; var positions = [ 'Bosh VZHIH-101', 'Ariston WHO-D', 'Atlant Mattel 2016', 'Wirpool FLASH black edition', 'Bosh VH1Z-024' ]; var prices = [ 10000, 4800, 9200, 2500, 5700 ]; var hits = []; function createObj(arrayName) { return arrayName.forEach(function(index){ var hash = {}; if (arrayName == positions){ hash.name = index; } else { hash.price = index; } hits.push(hash); }); } createObj (positions); createObj (prices); hits; Подправьте, пожалуйста. |
И как удалить одну из тем? Их почему-то две образовалось...
|
Цитата:
|
Цитата:
|
Цитата:
|
Цитата:
Цитата:
'use strict'; var positions = [ 'Bosh VZHIH-101', 'Ariston WHO-D', 'Atlant Mattel 2016', 'Wirpool FLASH black edition', 'Bosh VH1Z-024' ]; var prices = [ 10000, 4800, 9200, 2500, 5700 ]; var hits = []; function createObj(arrayName1, arrayName2) { return function(){ for (let i = 0; i<arrayName1.length; i++){ var hash = {}; hash.name = arrayName1[i]; hash.price = arrayName2[i]; hits.push(hash); } }; } createObj (positions, prices); hits; Но такой вариант вообще работать не хочет. |
Лучше тогда не forEach(), а map():
var positions = [ 'Bosh VZHIH-101', 'Ariston WHO-D', 'Atlant Mattel 2016', 'Wirpool FLASH black edition', 'Bosh VH1Z-024' ], prices = [ 10000, 4800, 9200, 2500, 5700 ], obj = positions.map(function(item, index) { return {'name' : item, 'price' : prices[index]} }) console.dir(obj) |
Цитата:
Красиво! Нечего сказать! Пойду обновлю инфу о map в своей голове. Спасибо большое! |
Часовой пояс GMT +3, время: 11:02. |