I am having 2 element list which is like this,
a = ['first_name', 'user']
b = ['last_name', 'abcd']
I want to convert it into,
{
'first_name' : 'user',
'last_name' : 'abcd'
}
This is what I tried:
a = ['first_name', 'user'] b = ['last_name', 'abcd'] new_dict = {} new_dict[a[0]] = a[1] new_dict[b[0]] = b[1] console.log(new_dict)
Are there any simple/native JS method than this?
您可以将a和b数组放置在外部数组中,然后将该数组简化为单个对象。
var o = [a,b].reduce(function(p, c) { p[c[0]] = c[1]; return p; }, {});
You can use Object.assign
with map()
and spread syntax.
var a = ['first_name', 'user'], b = ['last_name', 'abcd'] var obj = Object.assign({}, ...[a, b].map(([k, v]) => ({[k]: v}))) console.log(obj)
You could use Array#reduce
with Object.assign
and computed property names with a previous destructuring assignment .
var a = ['first_name', 'user'], b = ['last_name', 'abcd'], object = [a, b].reduce((r, [k, v]) => Object.assign(r, { [k]: v }), {}); console.log(object);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.