Replace Element in JSON with a element in a Javascript array - javascript

I have this JSON
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
and I have this JSON
{"computers":[{"id":"7bc530","name":"Dell","description":"Dell"},
{"id":"f30ef","name":"HP","description":"HP"},
{"id":"9e6d","name":"Compaq","description":"Compaq"},
{"id":"4d8665a3","name":"Toshiba","description":"Toshiba"},
{"id":"4fe1457","name":"Asus","description":"Asus"},
{"id":"4a18d27","name":"Acer","description":"Acer"}]}
I want to replace the "serial" element in the first JSON with the "Description" in this one. The reason why I need it in one JSON is that I am using a DataTable and I can only pass one JSON in.
I'm not sure how I can do this in Javascript / JQuery?

You can accomplish this without any jQuery by setting up small function:
(see the demo fiddle)
function replaceSerial (data1, data2) {
var descs = {}, computers = data2['computers'], final = data1;
for (var i = 0; i < computers.length; i++ ) {
descs[computers[i]['id']] = computers[i]['description'];
}
for (var i = 0; i < data1.length; i++) {
final[i]['serial'] = descs[data1[i]['serial']];
}
return final;
}
Then just save your two pieces of JSON into variables and invoke the function:
var json1, json2, mergedJson;
json1 = // DATA IN FIRST JSON;
json2 = // DATA IN SECOND JSON;
mergedJson = replaceSerial (json1, json2);

Assuming your first object is called to and the second object is called from
// Iterate over each entry in to
to.forEach(function(value) {
// In each iteration find elements in from where the id is the same
// as the serial of the current value of to
var description = from.computers.filter(function(element){
if (element.id == value.serial) return true;
});
// Copy description of first found object in the description property of
// the current object
value.description = description[0].description;
// Unset serial?
delete value.serial;
});
DEMO

Related

Find common id field between two seperate array object and merge it angular js

I have two separate data array objects with multiple fields:
This is how the data object array looks like with the eventId field in it too.
The annotateData object has eventId field that is also present in the data object. I want to check which data element has the same eventId present in the annotateData and then merge that annotateData element to the data object element. So the output will have data object with annotateObject fields added to it.
data: [{
0:{ annotateData fields + already present data fields} //if eventId matches
}]
Is there a more efficient way to do so rather than running the loop through the entire data object?
I don't think that there is another efficient way of doing this rather than looping. Although I would implement a few helper methods to iterate over and merge (as given here):
Array.prototype.indexOfWithKeyValue = function(key, value) {
var index = -1;
var _this = this;
for (var i = 0; i < this.length; i++) {
var item = _this[i];
if (item[key] === value) {
index = i;
break;
}
}
return index;
};
Array.prototype.find = function(key, value) {
var index = this.indexOfWithKeyValue(key, value);
return this[index];
};
And then iterate over:
var annotateData = []; // sample data
var data = []; // sample data
angular.forEach(annotateData, function(aData) {
var matchingData = data.find("eventId", aData.eventId);
if (matchingData) {
// Matching fields from "annotateData" will be merged over "data"
angular.merge(matchingData, aData);
}
});

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Check json data for value and then get its key

I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.
Code:
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
})
}
Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.
You can loop through the array and then through the object properties and make a new object using the colors as keys
var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}];
var new_response = {};
response.forEach(function(obj){
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = [];
new_response[obj[prop]].push(prop);
}
}
})
console.log(new_response);
The you can use the object for your needs as
new_response["red"]
giving you the list of all key with red value.
you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties.
So you can test the value and get keys for the value "yellow" or "red"
response.forEach(function(element) {
for (k in element) {
if (element[k]=="red" or element[k]=="yellow") {
// k is the key
}
}
});
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
for (i = 0; i < response.length; i++) { // iterate over response array
var item = response[i]; // get item from array
var key = Object.keys(item)[0]; // get the key of the item
var value = item[key]; // get the value of the item
if (value === 'yellow' || value === 'red') {
// do something, like adding it to a list
}
}
});
}

appendgrid - Getting grid data as a JSON Object instead of regular serialization

In the example listed here, how can I get the grid data as JSON?
Reference Link
The JQuery Serialize works, but it would be nice if I am able to get each row as a JSON Object, so I can parse the data.?
You can use the .appendGrid('getAllValue') function to get the grid data as javascript objects. You can parse them directly or encode them as JSON.
Example:
var data = $('#tblAppendGrid').appendGrid('getAllValue')
returns an array where each element is the data from one table row as object.
data[0] will be the first row.
JSON.stringify(data) will be a JSON string with all the data from your table
You can create element on run time, as per the JSON object length, you have to use for each or simple for loop and iterate the json data upto length.
Like :
for(var i=0; i<=json_object.length; i++) {
console.log(json_object.user[i].name); var ele_block =
document.createElement('div'); $(ele_block).addClass("block"+i);
ele_block.appendChild(block_name);
$("#name_block").append(ele_block);
}
Create an element where the newly generated data will be added.
<div id="name_block"></div>
You can just use JQuery Serialize to get the seriesed string and then use the helper function uri_decoder to decode it to an Object.
var decode, seriesed, uri_decoder;
seriesed = "a=1&b=2&c=3&d=4&e=5";
uri_decoder = function(component_unpacker) {
if (component_unpacker == null) {
component_unpacker = (function(s) {
return s;
});
}
return function(str) {
var d, i, j, k, len, ref, ref1, ref2, s, v;
d = {};
ref1 = (ref = str.match(/[^?=&]+=[^&]*/g)) != null ? ref : [];
for (i = 0, len = ref1.length; i < len; i++) {
s = ref1[i];
ref2 = s.match(/([^=]+)=(.*)/), j = ref2.length - 2, k = ref2[j++], v = ref2[j++];
d[decodeURIComponent(k)] = component_unpacker(decodeURIComponent(v));
}
return d;
};
};
decode = uri_decoder();
console.log(json(decode(seriesed)));
try these code here
this util is provided by this project.

How to parse JSON data when the property name is not known in advance?

Here is my response code in jQuery:
var response = $.parseJSON(response);
for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}
Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.
I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?
Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.
var group = response.groupIds[i];
var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}
Your question's response format contains only one key-value pair. The code can then be reduced to:
var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];
If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.
for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}
Use a for..in loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.

Categories