需要向处于状态的数组添加对象

时间:2019-03-29 10:15:06

标签: javascript arrays reactjs object

我需要将一个对象添加到数组的最后一个对象

我有一个数组,其中包含处于类状态的对象

state={
items:[{key:"333",val:"Hi"},{key:"555", val:"Iam"}]
}

我需要在最后一个项目对象处添加一个过滤器对象

items:[{key:"333",val:"Hi"},{key:"555", val:"Iam",filter:{refine:true}}]

我尝试了以下一个

    (this.state.items.length-1).concat({filters:{
        refine:true
    }}

3 个答案:

答案 0 :(得分:2)

您可以使用index数组方法来访问最后一个对象,对其进行修改并更新状态数组

let state={
    items:[{key:"333",val:"Hi"},{key:"555", val:"Iam"}]
}
let last = state.items[state.items.length - 1];
last = {...last, filter:{refine:true}};

const newState = {
  ...state,
  items: [
      ...state.items.slice(0, -1),
      last
  ]
}

console.log(newState);

答案 1 :(得分:-1)

您可以采用最后一个元素,然后将obj合并到该元素中,然后再将其再次添加到数组末尾

let state={items:[{key:"333",val:"Hi"},{key:"555", val:"Iam"}]}

let obj = {filter:{refine:true}}

let add = (initial,obj) => {
  let last = initial[initial.length-1]
  let arr = [...initial].slice(0,-2)
  return [...initial, {...last, ...obj}]
}
state.items = add(state.items,obj)

console.log(state)

答案 2 :(得分:-1)

有一些小帮手....

f.write(r"""<rect x="0" y="0" width="%s"

这很容易:

 const lens = (key, fn) => obj => ({ ...obj, [key]: fn(obj[key]) });
 const mapIndex = (index, fn) => arr => arr.map((it, i) => i === (index + arr.length) % arr.length ? fn(it) : it);