javascript - VueJs - 将数组中的对象检索到新的对象数组中

标签 javascript arrays vue.js

任何人都可以帮我找到一种从对象数组返回对象的方法,以将所有对象连接到一个新的对象数组中,并使用对象名称而不是键。

array = [
  1: {
    cart: { fruits: {}, vegetables: {}, juices: {}}
  },
  2: {
    cart: { boxes: {}, tools: {}, bottles: {}}
  }
]

我正在尝试使用方法和计算属性在 Vuejs 中获取此特定输出,但我只能使用键作为普通数组获取输出。我需要对象名称而不是键。

预期输出

newArray = {
  cart: { fruits: {}, vegetables: {}, juices: {} boxes: {}, tools: {}, bottles: {}}
}

最佳答案

您可以使用reducedestructuring assignment并使用键以所需的格式合并对象。

let array = [{cart: { fruits: {}, vegetables: {}, juices: {}}},{cart: { boxes: {}, tools: {}, bottles: {}}}]

let op = array.reduce( (op,inp) => {
  let key = Object.keys(inp)[0]
  op[key] = {...op[key], ...inp[key]}
  return op
},{})

console.log(op)

关于javascript - VueJs - 将数组中的对象检索到新的对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007745/

相关文章:

c - 如何将指针数组归零

c++ - 我怎么知道我的数组在缓存中?

javascript - Bootstrap Vue 表 : show details when row clicked

javascript - 是否有一段 javascript 代码可以全部大写编译?

java - 如果数字在数组内,则删除索引

javascript - ReactJS 中的搜索和页面

javascript - 在 Vuetify 中,我如何制作一个动态列表,其中包含可单击的复选框以选择它们?

vue.js - @nuxt/auth 我可以使用参数发送刷新 token 吗?

javascript - javascript中的spring安全角色检查

javascript - 打字时向数字添加逗号