对象和嵌套对象生成

时间:2019-02-15 02:06:47

标签: javascript reactjs

我有一个自动生成的对象

this.state={
 fruits = []
}

这是我生成对象并将其插入fruits

的方式
const gen = (fruitname, price) => {
     this.setState({
        this.state.fruits: {...this.state.fruits, [fruitname]: price}
    })
}

输出是

{apple: "$2", banana: "$4", orange: "$6"}

现在我需要将类型嵌套在下面

   {apple: {
        "red": "$3",
        "Cripps": "$3",
        "Honeycrisp": "$5"
    }, 
    banana: {
        "small": "$4",
        "yellow": "$5",
        "green": "$2"
    },
    ...
   }

我将代码更新为

 const gen = (fruitname, price, types, eachPrice) => {
         this.setState({
            this.state.fruits: {...this.state.fruits, [fruitname]: { [types]: eachPrice} }
        })
    }

但是,每次输入每种水果,我只会得到一个对象

{苹果:{     “ red”:“ $ 3”, }, 香蕉: {     “ small”:“ $ 4”, }, ... }

如何保留所有?

2 个答案:

答案 0 :(得分:1)

首先克隆状态。

检查它是否已经在状态中,然后调整该特定键/值,然后进行操作,而不是创建一个新的键/值。

let state = {apple:{"red":"$3","Cripps":"$3","Honeycrisp":"$5"},banana:{"small":"$4","yellow":"$5","green":"$2"},}

function handleState(name,type,price){
  if(state[name]){
    let temp = {...state}
    temp[name][type] = price
    return {
      ...temp,
    }
  } else {
    return{
      ...state,
      [name]:{
        [type]: price
      }
    }
  }
}

console.log(handleState('apple','red','$20'))
console.log(handleState('test','red','$20'))

答案 1 :(得分:1)

如果我的理解正确,您正在尝试将types(键)的数组映射到对象中的值(eachPrice)。在这种情况下,您可以使用.reduce来实现。在这里,我将types数组简化为一个对象,其中每个type是一个键,每个值是其在eachPrice数组中的对应价格。

请参见以下示例:

let state = {}
const gen = (fruitname, types, eachPrice) => {
  state.fruit = {...state.fruit,
    [fruitname]: 
      types.reduce((acc, t, i) => (
        { ...acc, [t]: eachPrice[i]}
      ), {})
  }
}

gen("apple", ["red", "Cripps", "Honeycrisp"], ["$3", "$3", "$5"]);
gen("banana", ["small", "yellow", "green"], ["$4", "$5", "$2"]);
       
console.log(state.fruit);

请注意,此函数不使用price参数,因为您有eachPrice来定义价格。