gpt4 book ai didi

javascript - 将键推送到数组或 JavaScript 对象?

转载 作者:行者123 更新时间:2023-11-28 17:56:06 25 4
gpt4 key购买 nike

我需要创建一个具有特定键的数组或js对象,应将其推送到空数组或js对象。之后,我需要根据该键推送一些特定值,如下所示:

var arr = ["john":["jval1","jval2"], "matt":["mval1","mval2","mval3"]]

我知道这不是 js 对象或数组的正确表示法,但这就是想法。

这基本上就是我想做的事情:

var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"]; //my values for key john
var mvals = ["mval1","mval2","mval3"]; //my values for key matt

var arr = [];

for(var i in keys) arr.push(keys[i]) //pushing the names (I need to push this names as keys so next lines should work)

for(var i in jvals) arr["john"].push(jvals[i]) //Trying to push john values, which doesn't work because "john is not a key"
for(var i in mvals) arr["matt"].push(mvals[i]) //Same.

这根本不起作用,那么我该怎么做呢?

最佳答案

这是代码的更短版本,使用forEach

var keys = ["john","matt"];             //my keys
var jvals = ["jval1","jval2"]; //my values for key john
var mvals = ["mval1","mval2","mval3"]; //my values for key matt
var object = {}
keys.forEach(function(key, index) {
object[key] = index == 0 ? jvals.slice() : mvals.slice()
});
console.log(object)

关于javascript - 将键推送到数组或 JavaScript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44404273/

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