gpt4 book ai didi

javascript - 如何使用对象属性的名称动态引用数组

转载 作者:行者123 更新时间:2023-12-01 04:09:50 24 4
gpt4 key购买 nike

我想迭代对象的属性,并将每个属性的值推送到共享属性名称的数组。

如何使用属性名称动态引用数组名称?

var obj = {"timeslot": "6am-7am", "Monday": "5", "Tuesday": "9"};
var timeslot = [];
var monday = [];
var tuesday = [];

Object.keys(obj).forEach(function(key) {
console.log(key); // Returns "timeslot", "Monday", and "Tuesday" respectively
console.log(obj[key]); // Returns "6am-7am", "5" and "9" respectively
});

我想要的结果是三个数组,如下所示:

timeslot = ["6am-7am"];
monday = ["5"];
tuesday = ["9"];

最佳答案

使用Object#kaysArray#forEach迭代obj。如果变量位于全局范围内,则可以在 window 对象上使用方括号表示法 [] 将其分配给变量。

var obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };

var timeslot = [];
var monday = [];
var tuesday = [];

Object.keys(obj).forEach(function(key) {
window[key.toLowerCase()].push(obj[key]);
});

console.log(timeslot, monday, tuesday);

如果没有,将数组收集到另一个对象中:

var obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };

var result = {};

Object.keys(obj).forEach(function(key) {
result[key.toLowerCase()] = [obj[key]];
});

console.log(result);

使用 ES6,您可以使用 Object#assignArray#map 进行解构来获取变量:

const obj = { "timeslot": "6am-7am", "Monday": "5", "Tuesday": "9" };

const { timeslot, monday, tuesday } = Object.assign(...Object.keys(obj).map((key) => ({
[key.toLowerCase()]: obj[key]
})));

console.log(timeslot, monday, tuesday);

关于javascript - 如何使用对象属性的名称动态引用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579975/

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