gpt4 book ai didi

javascript - 将对象重组为二维数组对象

转载 作者:行者123 更新时间:2023-12-01 00:36:17 26 4
gpt4 key购买 nike

我想将疼痛对象重组为二维数组对象。

最初,我有这样的东西:

{ 
"education_histories.0.school":[
"The education_histories.0.school field is required."
],
"education_histories.0.degree":[
"The education_histories.0.degree field is required."
],
"education_histories.1.school":[
"The education_histories.1.school field is required."
],
"education_histories.1.degree":[
"The education_histories.1.degree field is required."
],
}

我想将其重组为:

[ 
{
"school":[
"The education_histories.0.school field is required."
],
"degree":[
"The education_histories.0.degree field is required."
]
},
{
"school":[
"The education_histories.1.school field is required."
],
"degree":[
"The education_histories.1.degree field is required."
]
}
]

目前,我一直在尝试做这样的事情:

let validationErrors = []    

$.each(this.errors, (key, value) => {
let splitKey = key.split('.')

validationErrors[splitKey[1]] = { [splitKey[2]]: value }
})

当然,这不会起作用,因为它一直覆盖到最后一轮。输出如下:

    [ 
{
"degree":[
"The education_histories.0.degree field is required."
]
},
{
"degree":[
"The education_histories.1.degree field is required."
]
}
]

我希望我能做类似的事情

let validationErrors = []    

$.each(this.errors, (key, value) => {
let splitKey = key.split('.')

validationErrors[splitKey[1]][splitKey[2]] = value
})

但这也行不通。它说“TypeError:无法设置未定义的属性'school'”

任何帮助将不胜感激。

最佳答案

你不必做太多改变。如果该对象不存在,则创建它,否则只需设置其属性。您还可以使用对象解构,并且不需要 jQuery:

  let validationErrors = []    

for(const [key, value] of Object.entries(this.errors)) {
let [ , index, name] = key.split('.');

if(!validationErrors[index]) valudationErrors[index] = {};
validationErrors[index][name] = value;
}

关于javascript - 将对象重组为二维数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109323/

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