gpt4 book ai didi

javascript - Reactjs : Adding element to array object in Json

转载 作者:行者123 更新时间:2023-12-01 02:25:58 26 4
gpt4 key购买 nike

我刚刚开始使用reactjs并处理表单组件(formsy)。我试图将元素添加到现有的数组元素中,但我无法这样做。以下是我已经尝试过的以及到目前为止我所得到的。

JSON 对象 -

{
"details": {
"someInnerObj": "v3",
"innerObj": {
"key1": "",
"key2": ""
},
"ArrayObject": [{
"type": "sometype",
"somedesign": {
"A": "",
"B": "",
"C": "",
"D": ""
},
"somedev": {
"a": "",
"b": "",
"c": "",
"d": ""
}
}
],
"code": "code",
"isThis": "true"
}
}

我在这里想要实现的是向 ArrayObject 添加元素,如下所示

"ArrayObject": [{
"type": "sometype",
"somedesign": {
"A": "",
"B": "",
"C": "",
"D": ""
},
"somedev": {
"a": "",
"b": "",
"c": "",
"d": ""
}
},
{
"type": "sometype1",
"somedesing1": {
"A1": "",
"B1": "",
"C1": "",
"D1": ""
},
"somedev1": {
"a1": "",
"b1": "",
"c1": "",
"d1": ""
}
}
]

我使用 json 对象的字段值来放置新元素“详细信息.ArrayObject[1]”。但它不是添加新元素而是创建新键(如下所示)并删除现有的 -

"ArrayObject": {
"[1]": {
"type": "sometype1",
"somedesing1": {
"A1": "",
"B1": "",
"C1": "",
"D1": ""
},
"somedev1": {
"a1": "",
"b1": "",
"c1": "",
"d1": ""
}
}
}

有人可以帮忙吗?

谢谢。

最佳答案

您可以使用spread operator syntax喜欢

    const data = {
"details": {
"someInnerObj": "v3",
"innerObj": {
"key1": "",
"key2": ""
},
"ArrayObject": [{
"type": "sometype",
"somedesign": {
"A": "",
"B": "",
"C": "",
"D": ""
},
"somedev": {
"a": "",
"b": "",
"c": "",
"d": ""
}
}
],
"code": "code",
"isThis": "true"
}
}

const newData = {
"type": "sometype1",
"somedesing1": {
"A1": "",
"B1": "",
"C1": "",
"D1": ""
},
"somedev1": {
"a1": "",
"b1": "",
"c1": "",
"d1": ""
}
}


const res = {
...data,
details: {
...data.details,
ArrayObject: [
...data.details.ArrayObject,
newData
]
}
}

console.log(res);

关于javascript - Reactjs : Adding element to array object in Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com