Loop through JSON data in javascript - javascript

I have a php script returning JSON encoded data like below:
{
"1":
{
"from":"Vimbai Jongwe",
"msg":"wadii"
},
"2":
{
"from":"Brian Dube",
"msg":"Eh Chibaba"
}
}
So now i want to access that data using the keys from and msg to be displayed somewhere.

You can loop it like below
var data = {
"1":
{
"from":"Vimbai Jongwe",
"msg":"wadii"
},
"2":
{
"from":"Brian Dube",
"msg":"Eh Chibaba"
}
}
for(var d in data){
console.log(data[d].from +"->"+data[d].msg);
}

Try below code you can loop and print as in below code
a = {
"1":
{
"from":"Vimbai Jongwe",
"msg":"wadii"
},
"2":
{
"from":"Brian Dube",
"msg":"Eh Chibaba"
}
};
for(var i in a){
console.log(a[i].from);
console.log(a[i].msg);
}

Related

How to push a consecutive number as string into an json object?

I want to push some data into a JSON file, which has just only consecutive numbers as keys and hash string as a value.
var readyFiles = JSON.parse(fs.readFileSync('requests.json', 'utf8'));
console.log(readyFiles)
const num = readyFiles.length
readyFiles.fileHashList.push({ num : _fileHash })
console.log(readyFiles)
var json = JSON.stringify(readyFiles)
fs.writeFileSync('requests.json', json, 'utf8');
the expected output should be like that:
{
"fileHashList": [
{
"1": "QmWpVdqGqPGo9ApLErzxBYfxD2eABKtYCQYCXQpnbYWjro"
},
{
"2": "QmTYsKnWBsVQTC1ioBHX7VWeY9tZLJXXzxuVkGiBSdBDea"
},
{
"3": "QmPiszxoFdCfwtLvWihaqFuBVpbU168WNVDbHUqtmuCDj3"
},
{
"4": "QmdLQ8TTg7EvJ4jvvbQiNWQUniKz6yKQugsvzVTMwNLJu1"
},
{
"5": "QmcziropQqSUDbNfAkYBwsLQXdEVf9N88Nqz4K1dfKeQGL"
},
{
"6": "QmSiEYVCY8G7zrc5X8UamkA6TymDyAg8dM39L7qnNFt7tY"
}
]
}
but instead, the actual behaviour is that:
{
"fileHashList": [
{
"1": "QmWpVdqGqPGo9ApLErzxBYfxD2eABKtYCQYCXQpnbYWjro"
},
{
"2": "QmTYsKnWBsVQTC1ioBHX7VWeY9tZLJXXzxuVkGiBSdBDea"
},
{
"3": "QmPiszxoFdCfwtLvWihaqFuBVpbU168WNVDbHUqtmuCDj3"
},
{
"4": "QmdLQ8TTg7EvJ4jvvbQiNWQUniKz6yKQugsvzVTMwNLJu1"
},
{
"5": "QmcziropQqSUDbNfAkYBwsLQXdEVf9N88Nqz4K1dfKeQGL"
},
{
"num": "QmSiEYVCY8G7zrc5X8UamkA6TymDyAg8dM39L7qnNFt7tY"
}
]
}
as you can see, there is 'num' as key in the last entry.
How can I have the next number of the keys there, espacially "6" in the above case?
const readyFiles = JSON.parse(fs.readFileSync('requests.json', 'utf8'));
const readyFilesKeys = Object.keys(readyFiles.fileHashList);
const countKey = readyFilesKeys.length + 1;
readyFiles.fileHashList.push({ [countKey]: _fileHash })
var json = JSON.stringify(readyFiles)
fs.writeFileSync('requests.json', json, 'utf8');
count the keys and + 1
use brackets [] outside the keys makes it possible, as #Taplar commented (THANKS :) )

Parse the JSON data in javascript

I Have following JSON data, I need to iterate this data based on Keytype in JAVASCRIPT.
It should return record from only the passed key code.
Say i need record from 438 means it should give me only following data.
(ex:"K": "43800001", "D": "Data1")
{
"GroupCode": {
"PickType": [
{
"#KeyType": "438",
"R": [
{
"K": "43800001",
"D": "Data1"
}
]
},
{
"#KeyType": "439",
"R": [
{
"K": "43900001",
"D": "Data2"
}
]
},
{
"#KeyType": "440",
"R": [
{
"K": "44000001",
"D": "Data3"
}
]
},
{
"#KeyType": "441",
"R": [
{
"K": "44100001",
"D": "Data4"
}
]
}
]
}
}
as I'm not good in java script and new to it, i haven't tried coding for this. Please help me in getting the data.
Let us say the above is stored in a variable obj. You can get the result via following
var result = obj.GroupCode.PickType.filter(function(item){
return item["#KeyType"] === "438"
}).map(function(item){
return item.R[0];
});
Please note, result is an array. If you have unique object against the condition then for that you will have to check the length of array and then extract the object i.e. result[0] or result.shift()
Working Fiddle here
function getByKeyType(keytype) {
for(i in f.GroupCode.PickType) {
if(f.GroupCode.PickType[i].KeyType == keytype) {
return f.GroupCode.PickType[i].R[0];
}
}
return null;
}
alert(getByKeyType(438).K)
alert(getByKeyType(438).D)
Try this
function getByKeyType(keytype) {
for(i in f.GroupCode.PickType) {
if(f.GroupCode.PickType[i].KeyType == keytype) {
return f.GroupCode.PickType[i].R[0];
}
}
return null;
}
Try a simple jquery each loop and a if:
jquery:
$.each(obj.GroupCode.PickType,function(i,v){
if (v["#KeyType"] == 438) {
console.log(v.R)//v.R[0];
}
});
javascript:
for(v in obj.GroupCode.PickType) {
if (v["#KeyType"] == 438) {
console.log(v.R)//v.R[0];
}
}

JavaScript - Processing and restructuring JSON not working

I'm trying to process a json file and create a new one, but it does not work.
The structure of an old json is something like this:
[
{
"3":{
"value":2
},
"4":{
"value":1
}
},
{
"3":{
"value":6
},
"4":{
"value":1
}
}...and so on
What I'm trying to do is to create a new json object, which will have only two objects 0 and 1 and inside each of them there will be values from indexes 3 and 4 from the old one, which should look something like this:
{
"0":{
"0":[
{
"0":2
}
],
"1":[
{
"0":6
}
]..and so on
},
"1":{
"0":[
{
"0":1
}
],
"1":[
{
"0":1
}
]..and so on
}
}
The problem is that when I process and cook the old json the output for both indexes(0,1) is the same. I'm trying to loop it through 3 and 4 and assign those values into the new array but something is not quite right.
Fraction of the code:
//loop through the keysIndex
for (var c in keysIndex) {
//the new json has to be 2 objects, hence the below
newData[c] = {};
var vallueArr = [];
var newObj = {
0: oldData[i][keysIndex[c]].value
}
vallueArr.push(newObj);
objInNewData[entries] = vallueArr;
//the problem is somehwere here, it is appending twice the same
//objInNewData and not both 3 and 4 individually
newData[c] = objInNewData;
}
Hers's the whole logic: PLUNKER
Can someone please help as I cannot get my head around this :(
Many thanks
As I mentioned above, the use of index of keys of objects is not a good idea, because objects in Javascript have no defined order. For ordered items I suggest to use an array instead.
var data = [
{
"3": { "value": 2 },
"4": { "value": 1 }
}, {
"3": { "value": 6 },
"4": { "value": 1 }
}
],
keys = Object.keys(data[0]), // <-- ATTENTION!
obj = {};
data.forEach(function (a, i) {
keys.forEach(function (k, j) {
obj[j] = obj[j] || {};
obj[j][i] = obj[j][i] || [];
obj[j][i].push({ '0': a[k].value });
});
});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

Pull out certain nested objects

I have a series of nested objects like this:
data = {"12345":{"value":{"1":"2","3":"4"}},
{"12346":{"value":{"5":"6","7":"8"}},
{"12347":{"value":{"9":"0","11":"22"}}
I would like to create a function to grab certain objects within this grouping. For example...
grabObject(12345);
would return:
{"value":{"1":"2","3":"4"}}
Any help you could provide would be great.
You don't need anything more than this:
function grabObject(id) {
return data[id];
}
After making some fixes to your syntax, here's a working jsFiddle: http://jsfiddle.net/jfriend00/04no0bvm/
var data = [
{
"12345": {
"value": {
"1": "2",
"3": "4"
}
}
},
{
"12346": {
"value": {
"5": "6",
"7": "8"
}
}
},
{
"12347": {
"value": {
"9": "0",
"11": "22"
}
}
}
];
function grabObject(id) {
var result;
for (i = 0; i < data.length; i++) {
for (var k in data[i]){
if(k == id) {
result = data[i][k];
}
}
}
return result;
}
console.log(grabObject('12345'));
This is the code I tested check and let me know

how to construct a json object using info from several javascript arrays

I have two js arrays already, say: names and values (with the same length), now I would like to construct a json object in certain format? For example:
names = ["label1","label2","label3"];
values = [[[0,1],[1,9],[2,10]],[[0,89],[1,91],[2,1]],[[0,1],[1,9],[2,10]]];
I would like to have a json array data_spec in this format:
[{
label:"label1",
data:[[0,1],[1,9],[2,10]]
},
{
label:"label2",
data:[[0,89],[1,91],[2,1]]
},
{
label:"label3",
data:[[0,1],[1,9],[2,10]]
}]
Could anyone tell one how? Thanks a lot!
For a bit of variety and a check,
var data_spec = [];
if (names.length != values.length) {
// panic, throw an exception, log an error or just return an empty array
} else {
for (var i=0, name; name = names[i]; i++) { // assuming a non-sparse array
data_spec[i] = {
label : name,
data : values[i]
};
}
}
That is, non-sparse and not containing anything else that would evaluate to false.
If your framework has an each function added to Array and you don't care about performance,
var data_spec = [];
names.each(function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework is a clean one like Dojo and puts it somewhere else (ex is Dojo),
var data_spec = [];
dojo.forEach(names, function(name) {
data_spec.push({ label : name, data : values[names.indexOf(name)] });
});
If your framework has an each function that returns an Array of identical length with the results of every operation at their expected position,
var data_spec = arrayOfResultsEach(names, function(name) {
return { label : name, data : values[names.indexOf(name)] };
});
These are just for illustration, indexOf inside loops of arbitrary length is a major code smell.
Just use a loop (make sure the two arrays are of same length)
result = [];
for(var i=0, len=names.length; i < len; i++) {
result.push({label: names[i], data: values[i]});
}
var myArray =
[{
"label": "label1",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
},
{
"label": "label2",
"data" :
{
"0": "89",
"1": "91",
"2": "1"
}
},
{
"label": "label3",
"data" :
{
"0": "1",
"1": "9",
"2": "10"
}
}];
alert(myArray[0].data[2]);

Categories