将此转换为:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}要这样做:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"}就是..。{id:数量}
我找到了一个几乎能满足我需要的答案:Searching for an Object inside the JSON。但是这个答案对我没有帮助,因为它只在第一级(一个json对象)。我的问题在第二层(json对象中的json对象)。提前感谢!
发布于 2012-04-29 06:55:50
如果您不将JSON对象视为JSON对象,这会有所帮助。一旦通过JSON.parse运行JSON字符串,它就是一个本机JavaScript对象。
在JavaScript中,有两种访问对象的方法。
点号表示法
点符号是这样的
myObject.name
看到那个点了吗?您可以使用它来访问任何对象属性(它实际上可能是javascript中的另一个对象,只要它具有有效的点符号名称)。不能使用-、.和空格等字符。
方括号表示法(可以是另一个名称)
myObject["variableName"]
类似于点符号,但允许一些其他字符,如-和空格字符。做完全一样的事情。
使用这些符号很有用,因为我们可以访问嵌套属性。
myObj.foo.bar.baz()
现在让我们来看看你的JSON对象...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
`{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],`您可能希望自己温习一下JSON format,但在您的示例中,这里有一些线索……
{表示对象的开始。(请记住,整个JSON字符串本身就是一个对象。)
}表示对象的结尾。
"variable" (带引号!在JSON中很重要,但在访问/声明javascript对象时不重要)为您的对象分配一个属性。
:是JSON和JavaScript对象中的赋值操作符。:右侧的任何内容都是您分配给左侧属性的值。
,意味着你在一个对象中开始一个新的属性。
您可能知道内含,逗号的[]表示数组。
当我们通过JSON.parse(string)运行你的字符串时,我们将得到一个如下所示的对象...
var myResponse = JSON.parse(response);
现在,您可以将其用作本机JavaScript对象。您要查找的是"items“中的嵌套属性。
var items = myResponse.items; //alternatively you could just use myResponse.items
因为items是一个对象数组,所以我们需要遍历它,以便将现有对象转换为新对象。
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.结果现在是一个如下所示的对象:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}您可以使用方括号表示法访问属性。
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
发布于 2012-04-29 07:04:37
您可以尝试使用:
var obj = {
"items":[
{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}
],
"country":"JUS",
"region":"A",
"timeout":"FILLER"
};
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});然后,quantities将成为对象{"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}。forEach是JavaScript中数组对象的本机方法,允许您遍历数组对象的元素。你可能想把这段代码放在一个函数中:
function getQuantities(obj) {
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
return quantities;
}发布于 2012-04-29 06:52:13
您需要执行以下操作:
var newJSON = {};
for (var i = 0; i < oldJSON.items.length; i++) {
newJSON[oldJSON.items[i].id] = oldJSON.items[i].quantity;
}https://stackoverflow.com/questions/10368171
复制相似问题