我有这种对象数组:
[
{variable: "contactPhone", title: "Phone", type: "text"},
{variable: "contactName", title: "Name", type: "text"}
]
每次单击时,我都会在数组中动态添加新对象。实际上,它是对象之一的克隆,具体取决于一个用户单击了哪个对象。 因此,我需要像这样对它们进行排序,contactPhone始终位于顶部,contactName始终位于底部:
[
{variable: "contactPhone", title: "Phone", type: "text"},
{variable: "contactPhone", title: "Phone", type: "text"},
{variable: "contactPhone", title: "Phone", type: "text"},
{variable: "contactName", title: "Name", type: "text"},
{variable: "contactName", title: "Name", type: "text"},
]
这是我想做的,但是没有用。有任何想法吗 ?
addNewInput(i) {
const { data, index } = this.state
let cloned = { ...data[index].variables[i] }
const newData = this.state.data
newData[index].variables.push(cloned)
data[index].variables.sort((a, b) => (a.variable === b.variable ? 1 : -1))
this.setState({
data: newData,
})
}