创建Javascript未排序的数组对象

时间:2015-04-03 10:24:04

标签: javascript arrays

我想为此创建一个未排序的JavaScript数组对象我有两个数组

var degree_values = ['Bachelors', 'Doctoral / PhD', 'Masters', 'MBA', 'Professional Certifications'];
var degree_indexes = ["4", "3", "2", "1", "5"];
var values = {};     
for(var index in degree_values){
    values[degree_indexes[index]] = degree_values[index];
}
console.log(values);

输出

Object { 1="MBA", 2="Masters", 3="Doctoral / PhD", 4 = 'MBA', 5 = 'Professional Certifications'}

预期的输出

Object { 4 = 'MBA',  3="Doctoral / PhD", 2="Masters", 1="MBA", 5 = 'Professional Certifications'}

2 个答案:

答案 0 :(得分:0)

尝试将循环更改为for (i = 0; i < degree_values.length; i ++){格式,然后使用i作为数组中的位置来访问变量。

由于您无法依赖浏览器按顺序维护对象,如此处How to keep an Javascript object/array ordered while also maintaining key lookups?的答案所示,您可以构建一个javascript对象数组并按照其中的建议执行,即具有id和值对于每个元素。

以下是包含这些更改的代码:

var degree_values = ['Bachelors', 'Doctoral / PhD', 'Masters', 'MBA', 'Professional Certifications'];
var degree_indexes = ["4", "3", "2", "1", "5"];
var values = [];     
for (i = 0; i < degree_values.length; i ++){
    values[i] = {'id': degree_indexes[i], 'value' : degree_values[i]};
}
console.log(values);

这是我运行此代码的输出:

VM1067:12 [Object, Object, Object, Object, Object]
0: Object
    id: "4"
    value:     "Bachelors"
    __proto__: Object
1: Object
    id: "3"
    value: "Doctoral / PhD"
    __proto__:     Object
2: Object
    id: "2"
    value: "Masters"
    __proto__: Object
3: Object
    id: "1"
    value:     "MBA"
    __proto__: Object
4: Object
    id: "5"
    value: "Professional Certifications"
    __proto__: Object
length: 5
__proto__: Array[0]
undefined

答案 1 :(得分:0)

轻松使用开源项目jinqJs

See Fiddle

var degree_values = ['Bachelors', 'Doctoral / PhD', 'Masters', 'MBA', 'Professional Certifications'];
var degree_indexes = ["4", "3", "2", "1", "5"];

//Gets emails that are in current not in group
var result = jinqJs().from(degree_values).select(function(row,index){
    var obj = {};
    obj[degree_indexes[index]] = row;

    return obj;
});