我有一个数据集,其中有许多具有相似属性(输出)的设备。 (例如下面给出的 2)。我不明白的是如何使用新名称将每个设备分配给例如新的 div。数据集中可以有很多设备。我如何告诉我的代码每当有新设备时取出 bytes_read 和 bytes_writing 并将它们分配给新的 div 例如分配
"bdev0": {"Bytes_Read": 0, "Bytes_Written": 0} to div_one
"bdev1": {"Bytes_Read": 10, "Bytes_Written": 20 } to div_two
请注意,我不能使用像 data.devices[0] 这样的东西,因为有很多设备并且它们的名称不断变化,例如 bdev0、bdev1、bdev2、bde3 .. 这是给出的数据集示例:
var data = {
"devices": [
{
"Name": "bdev0",
"output": {
"IO_Operations": 0,
"Bytes_Read": 0,
"Bytes_Written": 0
}
},
{
"Name": "bdev1",
"output": {
"IO_Operations": 10,
"Bytes_Read": 20,
"Bytes_Written": 30
}
}
]
}
这就是我能走多远,但它创建了两个不同的字符串,但我如何将它们分别分配给两个不同的项目。这听起来真的很愚蠢,但我真的被困在这里,例如,如果我想将这些字符串分配给 var a 和 var b 我应该怎么做
function myData() {
for (var i in data.devices){
var obj = new Object();
obj.Bytes_read = data.devices[i].output.Bytes_Read;
obj.Bytes_written = data.devices[i].output.Bytes_Written;
var jsonString= JSON.stringify(obj);
console.log(jsonString)
}
}
myData(data)
结果
{"Bytes_read":0,"Bytes_written":0}
{"Bytes_read":20,"Bytes_written":30}
它为我提供了我想要的数据,但我无法弄清楚将这些集合分配给 var a 和 var b。
最佳答案
如果您知道设备的名称,则可以将其用作访问数据的 key 。
var data = {
"devices": [{
"Name": "bdev0",
"output": {
"IO_Operations": 0,
"Bytes_Read": 0,
"Bytes_Written": 0
}
}, {
"Name": "bdev1",
"output": {
"IO_Operations": 10,
"Bytes_Read": 20,
"Bytes_Written": 30
}
}]
},
selectedData = {};
data.devices.forEach(function (a) {
selectedData[a.Name] = {
Bytes_Read: a.output.Bytes_Read,
Bytes_Written: a.output.Bytes_Written
};
});
document.write('<pre>'+JSON.stringify(selectedData, 0, 4)+'</pre>');
更新:也许这就是您想要的。使用设备名称,函数 getDeviceInfo
返回信息。
function getDeviceInfo(deviceName) {
var obj = {};
data.devices.some(function (a) {
if (a.Name === deviceName) {
obj[deviceName] = {
Bytes_Read: a.output.Bytes_Read,
Bytes_Written: a.output.Bytes_Written
};
return true;
}
});
return obj;
}
var data = {
"devices": [{
"Name": "bdev0",
"output": {
"IO_Operations": 0,
"Bytes_Read": 0,
"Bytes_Written": 0
}
}, {
"Name": "bdev1",
"output": {
"IO_Operations": 10,
"Bytes_Read": 20,
"Bytes_Written": 30
}
}]
},
div_one = getDeviceInfo('bdev0'),
div_two = getDeviceInfo('bdev1');
document.write('<pre>' + JSON.stringify(div_one, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(div_two, 0, 4) + '</pre>');
关于javascript - 如何将同一数据集中的 json 字符串分配给不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33216470/