如何在javascript中创建密钥索引数组

时间:2017-11-02 06:26:49

标签: javascript angularjs arrays

我有一个类似的空白数组:WO_Attribute: [] (0)

我也有密钥: 363270

  

数组:{wosetid:" 363612",woattrvalueid:212122,woattrvalue:   "测试",woattrid:6842}

如何创建类似的数组如下:

"WO_Attribute": {
    "363270": [
        {
            "wosetid": 363270,
            "woattrvalueid": 5160601,
            "woattrvalue": "testing",
            "woattrid": 1602
        }
    ]
}

我使用了以下方法但是如果WO_Attribute是空白数组则它不起作用:

let WO_Attribute = [];
let resArr = [];
let resVal = { 
    wosetid: "363612", 
    woattrvalueid: 212122, 
    woattrvalue: "testing", 
    woattrid: 6842 
};

resArr.push(resVal);

WO_Attribute[key] = resArr;

感谢。

6 个答案:

答案 0 :(得分:0)

WO_Attribute更改为此类对象。

let WO_Attribute = {};
WO_Attribute["363270"] = resArr;

答案 1 :(得分:0)

您可以使用array.reduce()遍历数组并创建所需的对象。

const data = [{
  "wosetid": 363270,
  "woattrvalueid": 5160601,
  "woattrvalue": "testing",
  "woattrid": 1602
}, {
  "wosetid": 312485,
  "woattrvalueid": 5160602,
  "woattrvalue": "testing2",
  "woattrid": 1603
}];
const result = data.reduce((o, v) => { o[v.wosetid] = v; return o; }, {});
console.log(result);

答案 2 :(得分:0)

WO_AttributeObject而不是Array

  

javascript中对象和数组之间的区别在于   对象是键值对,其中键可以是字符串或数字,而数组是   有序的元素集,其中键按数值排序   从0开始。因此数组也是具有一些限制的对象和一些额外的数组特定属性和方法

let WO_Attribute = {}; //Initialize WO_Attribute as an empty object.


let resVal = {
                "wosetid": 363270,
                "woattrvalueid": 5160601,
                "woattrvalue": "testing",
                "woattrid": 1602
            }

/*add a property to the object with key '363270' and empty array as value.*/
WO_Attribute['363270'] = []; 

/*push the data object to the array*/
WO_Attribute[resVal.wosetid].push(resVal); 

答案 3 :(得分:0)

WO_Attribute需要是一个对象而不是数组

let WO_Attribute = {};
let key = "363270";
let resArr = [];

let resVal = {
  wosetid: "363612",
  woattrvalueid: 212122,
  woattrvalue: "testing",
  woattrid: 6842
};

resArr.push(resVal);

WO_Attribute[key] = resArr;
console.log(WO_Attribute)

答案 4 :(得分:0)

您可以使用Object代替Array,如果您想要迭代它,可以使用Object.keysObject.values方法来检查其键或值:



let WO_Attribute = {};

WO_Attribute['some_key_1'] = 'Some Value 1';
WO_Attribute['some_key_2'] = 'Some Value 2';

Object.keys(WO_Attribute).forEach(key => {
  console.log(WO_Attribute[key]);
  // some other stuff
});




答案 5 :(得分:0)

使用ES6,您可以将Array#mapspread syntax ...Object.assign一起使用。

var data = [{ wosetid: 363270, woattrvalueid: 5160601, woattrvalue: "testing", woattrid: 1602 }, { wosetid: 312485, woattrvalueid: 5160602, woattrvalue: "testing2", woattrid: 1603 }],
    result = Object.assign(...data.map(o => ({ [o.wosetid]: o })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }