gpt4 book ai didi

javascript - 将数组动态映射到嵌套对象

转载 作者:行者123 更新时间:2023-11-30 15:16:34 26 4
gpt4 key购买 nike

我想在提交时检索表单内容并将该数据映射到一个对象。

let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);

--要通过 POST 发送的模板对象

serializedToObject(serializedArray) {
let templateObject = {
privider: '',
pop3: {
host: '',
port: 110,
ssl: false
},
imap: {
host: '',
port: 993
},

email: '',
password: ''
};

for (let data in serializedArray) {
}

return templateObject;
}

--userData 的形式是

[Object, Object, Object, Object, Object, Object, Object]

-- 虽然 on object 是 form

Object: {
name: 'provider',
value: 'Aladin'
}

Object: {
name: 'imap-host',
value: '955'
}

Object: {
name: 'imap-port',
value:
}


Object: {
email: 'test@gmail.com',
value:
}

所以我需要一些帮助来将该对象数组映射到模板对象。AnyHelp 将不胜感激。

更新

[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]

最佳答案

每个serializedArray对象的name-property都有一个减号(-)表示嵌套对象,你可以按这些字符拆分然后设置值templateObject 的属性:

var serializedArray = [{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}];

// your defaults
var templateObject = {
provider: '',
pop3: {
host: '',
port: 110,
ssl: false
},
imap: {
host: '',
port: 993
},
email: '',
password: '',
};

serializedArray.forEach(function(obj) {
var deep = obj.name.split('-');
var key = deep.pop();

var level = templateObject;
deep.forEach(function(inner) {
var nested = level[inner];
var isObject = Object(nested) === nested;
level = isObject ? nested : {};
});

level[key] = obj.value;
});

// return templateObject; // when inside your function
console.log(templateObject);

关于javascript - 将数组动态映射到嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44375934/

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