在jQuery中使用特定键创建对象?

时间:2017-07-05 18:40:30

标签: jquery

如何使用jQuery创建以下对象:

{"41500":{"color":"black","qty":1},"41501":{"color":"red","qty":1}}

2 个答案:

答案 0 :(得分:0)



// you'll need them in an array
var arr = [];

// make an empty object
var obj = {};

// name a key and set the value as another obj
obj["41500"] = {
  "color": "black",
  "qty": 1
}
arr.push(obj);

// repeat
var obj = {};
obj["41501"] = {
  "color": "red",
  "qty": 1
}
arr.push(obj);

console.log(arr)




// // UPDATE

如果您需要索引值,请执行以下操作:



var array = [];
array[41500] = {
  "color": "black",
  "qty": 1
}
array[41501] = {
  "color": "red",
  "qty": 1
}
console.log(array[41500]);
var id = 41501;
console.log(array[id]);

// notice all the undefined values at the indexes
console.log(array);




答案 1 :(得分:0)

你不需要Jquery,只需使用普通的JS。有多种方法可以做到这一点。最简单的是:

var newObject = {"41500":{"color":"black","qty":1},"41501":{"color":"red","qty":1}}

您可能还希望使用JSON加载,特别是如果它的变量和文件。

var newObjectString = // the data from the file.
var newObject = JSON.parse(newObjectString)