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

时间:2017-06-07 05:33:09

标签: javascript

我需要创建一个带有特定键的数组或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.

这根本不起作用,所以我该怎么做?

4 个答案:

答案 0 :(得分:2)

以下是代码的更短版本,使用 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)

答案 1 :(得分:1)

这是你想要的吗?

将arr声明为对象并使用空数组添加键。然后按下您的键。



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[keys[i]]=[];

for(var i in jvals) arr["john"].push(jvals[i]);  
for(var i in mvals) arr["matt"].push(mvals[i]);

console.log(arr);




答案 2 :(得分:0)

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 = {}; // not []

for(var i in keys) arr.[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.

答案 3 :(得分:0)

好的,我知道您正在尝试做什么。代码的第一个问题是将arr的值压入其中之后,如何对keys数组进行处理:

for(...) {
    arr["john"].push(jvals[i]);
}

您正在做的几乎是说arr.john.push(...),但是arr没有名为john的数组属性。 arr所具有的是索引0处的元素,其值为"john"。即arr看起来很像arr = ["john", "matt"]

现在您要做的就是将arr更改为对象而不是数组。

这样,您的代码将如下所示:

var keys = ["john","matt"];
var jvals = ["jval1","jval2"];
var mvals = ["mval1","mval2","mval3"];

var arr = {};

arr["john"] = jvals;
arr["matt"] = mvals;

// Please don't do the above

// Doing the following (using an object literal) is much better, and what most will advice when creating objects in js.

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