Как я могу добавить 2 значения из массива внутри объекта внутри массива и показать его в поле снаружи?

#javascript #arrays #loops #object

#javascript #массивы #циклы #объект

Вопрос:

Я запутался с массивом внутри объекта внутри массива, хочу добавить поле внутри presentsData , вызвать его sumP , а внутри получить сумму значений внутри массива presents , используя массив prices .
Я попытался уменьшить, но это не сработало, я попробовал с помощью map и find, и я не получаю число, я получаю объект,и не могу понять, как зациклить оба значения
, это мой код:

     let presentsData= [
        {
          name: "Peter",
          presents: ["coffee","holidays"],
          money: 7000
        },
        {
          name: "Mario",
          presents: ["car","coal"],
          money: 300
        },
        {
          name: "Amanda",
          presents: ["computer","coal"],
          money: 300
        },
        {
          name: "David",
          presents: ["clothes", "car"],
          money: 2000
        }
    ]
    const prices= [
        {
          present: "coffee",
          price: 1
        },
        {
          present: "holidays",
          price: 1000
        },
        {
          present: "videogames",
          price: 40
        },
        {
          present: "computer",
          price: 600
        },
        {
          present: "tattoo",
          price: 30
        },
        {
          present: "clothes",
          price: 80
        },
        {
          present: "car",
          price: 6000
        },
        {
          present: "phone",
          price: 800
        },
        {
          present: "motorbike",
          price: 3500
        }
      ]
    const res =  presentsData.map(s => 
    ({
            ...s,
            sumP: prices.find(e=>e.present === s.presents[0] ? e.price: 0)
         
    }));
    console.log(res)
 

это то, чего я ожидал:

 [
    {
      name: "Peter",
      presents: ["coffee","holidays"],
      money: 7000
      sumP: (/*SUM OF PRESENTS'S VALUE*/)
    },
    {
      name: "Mario",
      presents: ["car","coal"],
      money: 300
      sumP: (/*SUM OF PRESENTS'S VALUE*/)
    },
    {
      name: "Amanda",
      presents: ["computer","coal"],
      money: 300
      sumP: (/*SUM OF PRESENTS'S VALUE*/)
    },
    {
      name: "David",
      presents: ["clothes", "car"],
      money: 2000
      sumP: (/*SUM OF PRESENTS'S VALUE*/)
    }
]
 

Ответ №1:

Преобразуйте prices в карту или объект price by present . Повторите данные с Array.map() помощью, и для каждого элемента уменьшите представленные значения до числа, взяв price их с prices карты.

 const fn = (data, prices) => {
  // creat a Map of price by present
  const pricesMap = new Map(prices.map(({ present, price }) => [present, price]))
  
  // map the data
  return data.map(o => ({
    ...o,
    // add sum by reducing the presents and taking the prices from the Map
    sumP: o.presents.reduce((acc, p) => acc   (pricesMap.get(p) ?? 0), 0)
  }))
}

const presentsData = [{"name":"Peter","presents":["coffee","holidays"],"money":7000},{"name":"Mario","presents":["car","coal"],"money":300},{"name":"Amanda","presents":["computer","coal"],"money":300},{"name":"David","presents":["clothes","car"],"money":2000}]
const prices = [{"present":"coffee","price":1},{"present":"holidays","price":1000},{"present":"videogames","price":40},{"present":"computer","price":600},{"present":"tattoo","price":30},{"present":"clothes","price":80},{"present":"car","price":6000},{"present":"phone","price":800},{"present":"motorbike","price":3500}]

const result = fn (presentsData, prices)
  
console.log(result)