Retrieving value of JSON object with string variable - javascript

I have a json data
var data={"mainVariants": [
{
"header": "Measure"
},
{
"header": "Disposal"
},
{
"header": "Stairs"
},
{
"header": "Furniture"
}
],
"Measure": {}}
var val1=data.mainVariants[0].header;//returned as "Measure"
Now i want to retrieve data.val1.Pls help

Try this
var val1 = data.mainVariants[0].getString("header");

You can just do var obj = data[val1]

Related

Create a nested JSON Object with Javascript

I´d like to create a JSON-Object for a Google API-Request. Only content is needed to change. My solution gives me an invalid JSON-Format and is more a hack. Is there an easier way to do this? Thank your for your hints.
The necessary format look like this:
{
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
JS
var cvs = cvs.substring('data:image/png;base64,'.length);
var json1 = '{"requests":[{ "image":{ "content":"'
var json2 = '"}, "features": [{"type":"DOCUMENT_TEXT_DETECTION"}] } ]}'
var entireJson = json1 + cvs + json2;
var ocrImage = JSON.stringify(entireJson);
What you have done in your example is initializing a Javascript Object.
JSON.parse(object_string); is not necessary. You may initialize it directly:
var ocrImage = {
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
console.log(ocrImage)

Lodash compare/merge object to array

I need to compare/merge 2 objects with diferent structure using Lodash.
data= [
{
"name": "EMPRESA",
"value": ""
},
{
"name": "DESIGEMPRESA",
"value": "CMIP"
},
{
"name": "UTILIZADOR",
"value": ""
},
{
"name": "CD_INDICADOR",
"value": ""
},
{
"name": "DT_INI_INDICADOR",
"value": ""
},
{
"name": "DT_INI",
"value": "2017-12-13"
},
.....
]
and
dbcolsData={
"EMPRESA": "",
"UTILIZADOR": "paulo.figueiredo",
"CD_INDICADOR": "",
"DT_INI_INDICADOR": "",
"DT_INI": "",
"DT_FIM": ""
}
The question is how i can fill the values of data with the values of dbcolsData ?
Lets say put the values of dbColsData in data
Thanks in advance
Try something like this:
_.forEach(data, function(object){
object.value = dbcolsData[object.name];
})
Use Array#map (or lodash's _.map()) to iterate the data, and get the results from dbcolsData:
var data = [{"name":"EMPRESA","value":""},{"name":"DESIGEMPRESA","value":"CMIP"},{"name":"UTILIZADOR","value":""},{"name":"CD_INDICADOR","value":""},{"name":"DT_INI_INDICADOR","value":""},{"name":"DT_INI","value":"2017-12-13"}];
var dbcolsData = {"EMPRESA":"","UTILIZADOR":"paulo.figueiredo","CD_INDICADOR":"","DT_INI_INDICADOR":"","DT_INI":"","DT_FIM":""};
var result = data.map(function(o) {
return Object.assign({ data: dbcolsData[o.name] }, o);
});
console.log(result);
Reduce data to the dbcolsData structure :
var myData = data.reduce((o, nvO) => Object.defineProperty(o, nvO.name, {value: nvO.value}), {})
->
Now you can use lodash comparison functions like _.isEqual :
_.isEqual(myData, dbcolsData)

Convert JSON object to JSON array with additional elements

I have the following JSON object
{
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
}
Is it possible to convert it to a JSON array with additional elements (url & status) in Javascript?
[
{
"url": "https://www.google.com",
"status": "200"
},
{
"url": "https://www.facebook.com",
"status": "200"
},
{
"url": "https://www.yahoo.com",
"status": "401"
},
{
"url": "https://www.friendster.com",
"status": "404"
}
]
Thank you for the tips.
Parse the string using JSON.parse, get all keys as an array and construct an array of objects with url and status properties
var json = '{\
"https://www.google.com": "200",\
"https://www.facebook.com": "200",\
"https://www.yahoo.com": "401",\
"https://www.friendster.com": "404"\
}';
var obj = JSON.parse(json);
var objWithUrlAndStatus = Object.keys(obj).map(function (key) {
return {
url: key,
status: obj[key]
}
});
console.log(objWithUrlAndStatus);
You can use jquery $.each
like this
var data = {
"https://www.google.com": "200",
"https://www.facebook.com": "200",
"https://www.yahoo.com": "401",
"https://www.friendster.com": "404"
};
var finalData=[];
$.each(data,function(index,val){
finalData.push({url:index,status:val});
});
console.log(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

loop through a json object in ajax response [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 8 years ago.
I am new to json so i am getting a json reponse from my ajax call
now i am stuck with looping the json object
here is my json
{
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
Can anyone help
You can use a for-in loop as follows:
var obj = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
for(var prop in obj) {
var item = obj[prop];
console.log(item);
}
Be aware that you will get the items in your log because you will get the pages property in addition to the numeric properties.
Save your JSON response in a variable
var variable = {
"0" : {
"image" : "http://test.com/systems.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "Oct-Dec-2013"
},
"1" : {
"image" : "http://test.com/energy.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "July-Sept-2013"
},
"pages" : 2
};
Then loop it using jquery
$.each(variable, function(index, value) {
alert(value.image);
alert(value.anchor_tag_link);
});
you can do this.
var json = JSON.parse(data);// here data is your response
for (var key in json) {
alert(json[key].image);// other also in the same way.
}
Example 1 :
success: function(responseData) {
for (var key in responseData) {
alert(responseData[key]);
}
}
Example 2 :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
alert(json.phoneNumber.number); //undefined
</script>
Sample Code
Please try the following code. You only have to replace "yourJSONObject" by the JSON array.
$.each( yourJSONObject, function( keyImg, valImg ) {
image = valImg[0];
anchor_tag_link = valImg[1];
title = valImg[2];
});
Regards,
you can loop through this like looping through javascript object :
for(var arg in object) {
object.hasOwnProperty(arg) {
process(object[arg]);
}
}
JQuery:
var JSON = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
};
if(JSON.pages >0)
{
for(var i=0; i<JSON.pages; i++)
{
$('table').append('<tr><td>'+JSON[i].title+'</td><td>'+JSON[i].image+'</td><td>'+JSON[i].anchor_tag_link+'</td></tr>');
}
}
HTML:
<table border="1"></table>

Appending to JSON object using JavaScript

I'm building the JSON object using JavaScript. How would I inset the following data to the bottom of the stack:
"hello": { "label":"Hello", "url":"#hello" }
in to the following variable:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
}
};
So the variable looks like:
var ListData = {
"main": {
"label":"Main",
"url":"#main"
},
"project": {
"label":"Project",
"url":"#project"
},
"settings": {
"label":"Settings",
"url":"#settings",
"subnav":[
{
"label":"Privacy",
"url":"#privacy"
},
{
"label":"Security",
"url":"#security"
},
{
"label":"Advanced",
"url":"#advanced"
}
]
},
"hello": {
"label":"Hello",
"url":"#hello"
}
};
I used the following code but it doesn't seem to work:
var NewData = '"hello": { "label":"Hello", "url":"#hello" }';
ListData.push(NewData);
You can insert it directly with an object literal:
ListData.hello = { label: "Hello", url: "#hello" };
If you are using jQuery, you can use the .extend() jQuery API like:
$.extend(ListData, {"hello": { "label":"Hello", "url":"#hello" }});
I have one more solution using underscore.js module,
var _ = require("underscore");
var src = {
"main": {
"label": "Main",
"url": "#main"
},
"project": {
"label": "Project",
"url": "#project"
},
"settings": {
"label": "Settings",
"url": "#settings",
"subnav": [
{
"label": "Privacy",
"url": "#privacy"
},
{
"label": "Security",
"url": "#security"
},
{
"label": "Advanced",
"url": "#advanced"
}
]
}
};
var dest = {"hello": { "label":"Hello", "url":"#hello" }};
var data = _.extend(src, dest);
console.log(JSON.stringify(data));
Required op :
{"main":{"label":"Main","url":"#main"},"project":{"label":"Project","url":"#project"},"settings":{"label":"Settings","url":"#settings","subnav":[{"label":"Privacy","url":"#privacy"},{"label":"Security","url":"#security"},{"label":"Advanced","url":"#advanced"}]},"hello":{"label":"Hello","url":"#hello"}}
Keeping with you object literal statements just add another object to your ListData object.
ListData.hello = { "label":"Hello", "url":"#hello" };
push is only for Javascript Arrays.
A JavaScript Object Literal is a comma-separated list of name/value pairs wrapped by a pair of curly braces.
To append the property name of encampment name with a value of Valley Forge to the bottom of the stack, simply add the property name after the JSON object with a dot syntax. Then specify the value. (See 'Append data' below)
You can also delete the appended name/value pair from the object literal. (See 'Delete data below')
// Start with some JSON
var myJson = { "name":"George Washington", "rank":"General", "serial":"102" };
// Append data
myJson.encampment = "Valley Forge";
// Delete data
delete myJson.encampment

Categories

Resources