向数组添加元素和对象

时间:2018-06-05 17:56:12

标签: javascript

这就是我要做的事情:

state={
  show:true,
  key:'',
  sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}

我需要向数据数组中添加元素,我需要将对象添加到sections数组

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

var state={
 show:true,
 key:'',
 sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}

state.sections.push({title:'new',data:['e','f']});
console.log(state.sections);

答案 1 :(得分:1)

使用push()功能将项目添加到数组中:

let state={
    show:true,
    key:'',
    sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}

state.sections[0].data.push('c');

state.sections.push({title:'title',data:['2','5']});
console.log(state.sections);

//for react setState
this.setState({
  state.sections: [...this.state.sections, {title:'title',data:['2','5']}]
})

答案 2 :(得分:1)

推出新栏目很简单:

state.sections.push({title:'someTitle',data:[2, 3]});

要推送新数据,您需要指定要推送的数据。例如,要进入test部分,您必须首先获得对test对象的引用,然后推送:

var state= {
  show:true,
  key:'',
  sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
 }

let section = state.sections.find(item => item.title == 'test')
section.data.push(3)

console.log(state)

这假设标题是唯一的,因为find()只找到第一个匹配的项目。如果您有可能搜索不存在的标题,您可能还想测试find()实际找到的内容。

相关问题