如何更改嵌套数组中的值

问题描述 投票:0回答:3

代码:

let fruits = [{
    name: 'apple',
    attributes: [{
        type: 'Granny Smith',
        color: 'green',
        isFavorite: true
      },
      {
        type: 'Ambrosia',
        color: 'red',
        isFavorite: true
      }
    ],
    isFavorite: true
  },
  {
    name: 'Pear',
    attributes: [{
        type: 'Asian',
        color: 'brown',
        isFavorite: true
      },
      {
        type: 'White Pear',
        color: 'white',
        isFavorite: false
      }
    ],
    isFavorite: true
  },
]

const fruitChecked = fruits.map(fruit => {
  return { ...fruit,
    isFavorite: true
  }
})

const fruitAttributesChecked = fruitChecked.map(fruit => {


  (fruit.attributes).map(attr => {
    return { ...attr,
      isFavorite: true
    }

  })
})

console.log(fruits)
console.log(fruitChecked)
console.log(fruitAttributesChecked)

我正在尝试将每个对象中的所有 isFavorite 值更改为 true,并将属性中的 isFavorite 值更改为 true。

但是,我得到了与fruitAttributesChecked的[未定义,未定义]类似的东西

我想要的结果如下:fruitAttributesChecked

fruitAttributesChecked =
[
   {name: 'apple', 
    attributes: [
          {type: 'Granny Smith', color:'green', isFavorite: true},
          {type: 'Ambrosia', color:'red', isFavorite: true}
    ], 
     isFavorite: true
   },
   {name: 'Pear', 
    attributes: [
          {type: 'Asian', color:'brown', isFavorite: true},
          {type: 'White Pear', color:'white', isFavorite: false}
    ], 
     isFavorite: true
   },
]

我在这里缺少什么?

javascript arrays nested array.prototype.map
3个回答
4
投票

您可以使用嵌套的

map()
返回对象中修改后的
attributes
数组。

let fruits = [{
    name: 'apple',
    attributes: [{
        type: 'Granny Smith',
        color: 'green',
        isFavorite: true
      },
      {
        type: 'Ambrosia',
        color: 'red',
        isFavorite: true
      }
    ],
    isFavorite: true
  },
  {
    name: 'Pear',
    attributes: [{
        type: 'Asian',
        color: 'brown',
        isFavorite: true
      },
      {
        type: 'White Pear',
        color: 'white',
        isFavorite: false
      }
    ],
    isFavorite: true
  },
]

const fruitChecked = fruits.map(fruit => ({ ...fruit,
  isFavorite: true,
  attributes: fruit.attributes.map(attribute => ({ ...attribute,
    isFavorite: true
  }))
}))

console.log(fruitChecked);


0
投票
const mappedFruits = fruits.map(fruit => {
    return {
        ...fruit,
        isFavorite: true,
        attributes: attributes.map(attribute => {
            return {
                ...attribute,
                isFavorite: true,
            }
        })
    }
})

0
投票

我要问一个问题: 如果属性本身包含属性[]怎么办 喜欢:

让水果= [{ 名称:'苹果', 属性: [{ 类型:“史密斯奶奶”, 颜色:“绿色”, 属性: [] }, { 类型:'安布罗西亚', 红色', 属性: [] } ], 属性: [] }, { 名称:'梨', 属性: [{ 类型:'亚洲', 颜色: '棕色', 属性: [] }, { 类型:“白梨”, 白颜色', 属性: [] } ], 属性: [] }, ]

并且必须将属性:[]替换为属性:null

© www.soinside.com 2019 - 2024. All rights reserved.