I want to get two values from my JSON array. It looks like that:
http://pastebin.com/tm5StsZ3
I need to get a ID and key from these arrays.
Please help me, thanks.
I am using newest node js.
ES6 syntax.
JSON.parse(data).map((item) => { item.id , item.key })
ES5
JSON.parse(data).map(function(item){ return {item.id , item.key }})
Loop through it like this:
var jsonData = JSON.parse(data);
for(var myobject in jsonData){
console.log("Id =" + myobject.id);
console.log("key = " + myobject.key);
}
or like this:
var jsonData = JSON.parse(data);
for(i = 0; i < jsonData.length; i++){
console.log("Id =" + jsonData[i].id);
console.log("key = " + jsonData[i].key);
}
var val1 = arr[0].id;
var k1 = arr[0].key;
var val2 = arr[1].id;
var k2 = arr[1].key;
To get the array lenght use arr.length
use map() function it will return te id and the key
var id = data.map(function(par){
return "id id :" +par.id+" key is: "+ par.key;
});
working see jsfiddle
Or you can is just a loop to access each key and id
for(i = 0; i < data.length; i++){
console.log("Id is :" + data[i].id+"key is : " + data[i].key);
}
Related
I'm looping over an Ajax result and populating the JSON in a select box, but not every JSON result is unique, some contain the same value.
I would like to check if there is already a value contained within the select box as the loop iterates, and if a value is the same, not to print it again, but for some reason my if check isn't working?
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults.Source.DataSourceName;
if ($('.SelectBox').find('option').text != sourcename) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
}
}
The text() is a method, so it needs parentheses, and it returns text of all <option> concatenated. There are better ways to do this, but an approach similar to yours can be by using a variable to save all the added text, so we can check this variable instead of having to check in the <option> elements:
var result = ["first", "second", "first", "third", "second"];
var options = {};
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults; //JsonResults.Source.DataSourceName;
if (!options[sourcename]) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
options[sourcename] = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="SelectBox"></select>
Note: I only used var sourcename = JsonResults; for the demo. Use your original line instead.
.text is a function, so you have to call it to get back the text in the option
for (var i = 0; i < result.length; i++) {
var JsonResults = result[i];
var sourcename = JsonResults.Source.DataSourceName;
if ($('.SelectBox').find('option').text() != sourcename) {
$('.SelectBox').append('<option>' + sourcename + '</option>');
}
}
For one thing, the jQuery method is .text() - it's not a static property. For another, your .find will give you the combined text of every <option>, which isn't what you want.
Try deduping the object before populating the HTML:
const sourceNames = results.map(result => result.Source.DataSourceName);
const dedupedSourceNames = sourceNames.map((sourceName, i) => sourceNames.lastIndexOf(sourceName) === i);
dedupedSourceNames.forEach(sourceName => {
$('.SelectBox').append('<option>' + sourceName + '</option>');
});
for (...) {
files.push(files[i]);
li_out.push({name : fileName, list_files : files});
}
How to get the Array of list_files by name?
var list_files_of_file3 = li_out[name == "file3" (?????)].list_files;
Array#find can be used in this case.
var list_files_of_file3 = li_out.find(o => o.name === "file3").list_files;
// Variable names changed for DEMO purpose
var files = [];
for (var i = 0; i < 10; i++) {
files.push({
name: 'fileName ' + i,
list_files: 'something ' + i
});
}
var res = files.find(o => o.name === 'fileName 3').list_files;
console.log(res);
How to get the Array of list_files by name?
using filter, try
var result = li_out.filter(function(item){ return item.name == "file3" });
Is it also possible to just return a property of the matching items
instead of the whole object? (below comment #MajidFouladpour)
Once you have got the result
var propertyNames = result.map(function(obj){ return obj.propertName; })
I'm getting error: setAttribute' on 'Element': 2 arguments required, but only 1 present.
I want to add attributes to an input but i'm avoiding repeats:
//putHolder.setAttribute("placeholder", "Product Name (required)");
//putHolder.setAttribute("ng-model", "vm.product.productName");
//putHolder.setAttribute("ng-minlength", "4");
//putHolder.setAttribute("ng-maxlength", "12");
//putHolder.removeAttribute("size");
I have used the following code but i can't get it right:
var putHolder = document.getElementById('CustomerID');
//var result = '{"placeholder":"Product Name (required)","ng-model":"vm.product.productName","ng-minlength":"4", "ng-maxlength":"12"}';
//$.each($.parseJSON(result), function (k, v) {
// putHolder.setAttribute(k + ' = ' + v);
// });
//or js please i prefer javascript
JSON.parse('{"placeholder":"Product Name (required)","ng-model":"vm.product.productName","ng-minlength":"4", "ng-maxlength":"12"}', function(k, v) {
putHolder.setAttribute(k + ' = ' + v);
});
I've also tried a loop but is just 1 elem like so:
var names = ["size", "value"];
for (var i = 0; i < names.length; i = ++i) {
var cadaUno = names[i];
putHolder.removeAttribute(cadaUno);
}
I hope someone can help thanks.
Hope someone can help - I'm new to js/jQuery so I'm hoping it's something really simple I'm missing here.
I'm trying to populate a dropdownlist with the xml result from below. The parseXML function works great and the result.push(valueid + "," + value) leaves me with the following:
1,Service
2,Breakdown
How do I get this into a dropdownlist please? Using the below, I get the error "Object doesn't support property or method 'split'"
Many thanks
leddy
function testFunction() {
var jobresults = "<resultset morerecords='0'> " +
"<result> " +
"<itt_jobtypeid>1</itt_jobtypeid> " +
"<itt_name>Service</itt_name> " +
"</result> " +
"<result> " +
"<itt_jobtypeid>2</itt_jobtypeid> " +
"<itt_name>Breakdown</itt_name> " +
"</result> " +
"</resultset> ";
var xml = parseXML(jobresults);
var jobid = xml.getElementsByTagName("itt_jobtypeid");
var jobname = xml.getElementsByTagName("itt_name");
var result = [];
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push(valueid + "," + value);
}
var jobtype = $("#ddlJobType");
$.each(result, function () {
var arr = result.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});
}
function parseXML(text) {
if (window.DOMParser) {
parser = new DOMParser();
doc = parser.parseFromString(text, "text/xml");
}
else { // Internet Explorer
doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(text);
}
return doc;
}
It can be simpler and cleaner if you optimize data structure for result array. Push an object with value and label so that you can simply use attr method directly after:
for (var i = 0; i < jobid.length; i++) {
var valueid = jobid[i].childNodes[0].nodeValue;
var value = jobname[i].childNodes[0].nodeValue;
// add longitude value to "result" array
result.push({value: valueid, label: value});
}
var jobtype = $("#ddlJobType");
$.each(result, function (i, obj) {
$('<option>').attr(obj).appendTo(jobtype);
});
See https://api.jquery.com/jquery.each/. The callback function gets each jobtype as parameter to the function.
Try changing the code to:
$.each(result, function (idx, value) {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
jobtype.append($("<option />").val(arr[0]).text(arr[1]));
}
});
suppose i have below function, which is getting jsonData in the form of jason, i validate the var jsonData to check for NaN ?
function save() {
var jsonData = getEnteredValue();
$.ajax({
type : 'POST',
url : 'saveSalesForecast.json',
data : 'jsonPostData=' + jsonData,
success : function() { //alert("success");
}
});
}
i only know how to replace NAN but don know how to check for NAN!
jsonData = JSON.parse(jsonData.replace(/\bNaN\b/g, "null"));
here is remaining function:(any field values can be string,numbers but it should not be NAN
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var jsonPostData = "[";
for ( var i = 0; i <= rowIds.length-1; i++) {
$("#salesForecastGrid").jqGrid('editCell', i, 2, false);
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', rowIds[i], 'forecastedSales'));
if (!((forecastedSales == "") || isNaN(forecastedSales) || (forecastedSales ==0))) {
if (ids.indexOf(rowIds[i])==-1){
ids.push(rowIds[i]);
}
}
}
for ( var i = 0; i <= ids.length-1; i++) {
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', ids[i], 'forecastedSales'));
var id = $("#salesForecastGrid").jqGrid('getCell', ids[i],
'id');
var date = $("#salesForecastGrid").jqGrid('getCell',
ids[i], 'day');
if (id < 0) {
id = 0;
}
var record = "{" + "id:" + id + "," + "date:" + date + ","
+ "forecastedSales:" + forecastedSales + "}";
jsonPostData = jsonPostData + record;
if (i != ids.length) {
jsonPostData = jsonPostData + ",";
}
}
jsonPostData += "]";
return jsonPostData;
}
Json Data like:
"[{id:68447,date:04-17-2014,forecastedSales:8420.42},{id:68448,date:04-18-2014,forecastedSales:9912.68},]"
Your problem is that you are creating the JSON manually, and thus end up with invalid JSON. Do yourself a favor and use JSON.stringify:
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var data = [];
// ...
for ( var i = 0; i < ids.length; i++) {
// ...
data.push(
{id: id, date: date, forecastedSales: forecastedSales}
);
}
return JSON.stringify(data);
}
Since NaN is not a valid value in JSON, it will automatically be converted to null. Example:
> JSON.stringify({a: NaN});
"{"a":null}"
For more info see Using native JSON.
NaN is not acceptable in JSON. JSON specification does not support NaN as a value. Even when javascript object has NaN value, it will be converted to null when you serialise to JSON format.
First of all, JSON is not an Javascript Object. JSON is general format which can be understand by all languages.