开发者问题收集

改变数组对象中的数据

2017-12-04
100

在 React 应用中,我有以下类型的数据:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

我想遍历 openclose 数组中的每个对象,并返回带有附加 type 字段的现有数据。例如:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

我正在尝试类似的事情,但它返回 undefined 而不是更改后的数据:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/

3个回答

您可以使用 reduce() 代替 forEach() 并返回对象。

const data = {"open":[{"id":1,"name":"test 1"},{"id":2,"name":"test 2"}],"close":[{"id":3,"name":"test 3"},{"id":4,"name":"test 4"}]}

function expandData (data) {
  return Object.keys(data)
    .reduce((r, k) => {
      r[k] = data[k].map(o => ({...o, type: 'alert'}))
       return r;
    }, {})
}

const result = expandData(data)
console.log(result)
Nenad Vracar
2017-12-04

你可以做

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
  return Object.keys(data).reduce((a, b) => {
    a[b] = data[b].map(e => ({
      ...e,
      type: 'alert'
    }))
    return a;
  }, {});
}

const result = expandData(data)
console.log(result)
marvel308
2017-12-04

此方法也可以遵循: 如果您需要它,请简单

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

function expandData (data) {
for(let key in data){
    if(data[key] instanceof Array){
    data[key].map(obj => {
    obj.type='alert'
  })
  }
}
return data
}

const result = expandData(data)
console.log(result)

https://jsfiddle.net/Lspd8345/2/

Harish Soni
2017-12-04