I am trying to retrieve the value of the JSON data and assign it to the JSON variable in the Angular like this:
$scope.bulkCreateRequest = function (jsonData) {
var data = {
"SERVICEREASON": jsonData.ServiceReason,
"SITE": jsonData.Site,
"FACILITY": jsonData.Location,
};
}
When I debug the application though the jsonData has content, it says defined for SERVICEREASON,SITE,FACILITY like below in Local
I am not sure what I am missing here.
jsonData seems to be an array, so jsonData[0]["ServiceReason"] should work, also first verify if its a string, if it is then you will have to first convert it to array of object like jsonData = JSON.parse(jsonData)
so final code might look like -
$scope.bulkCreateRequest = function (jsonData) {
jsonData = JSON.parse(jsonData);
var data = {
"SERVICEREASON": jsonData[0]["ServiceReason"], // this will also work
"SITE": jsonData[0].Site,
"FACILITY": jsonData[0].Location,
};
};
Related
I have a JSON response stored in a variable
savedData = {"ID":"{{ID}}","command":"ok"}. Also created an array variable
ID = [1,2,3]. I want to loop the JSON based on the array variable and apply the variable in the body in postman.
Example
{"ID":"1","command":"ok"},{"ID":"2","command":"ok"},{"ID":"3","command":"ok"}
I am new to postman and would appreciate your support.
Try this below :
let savedData = {"ID":[1,2,3],"command":"ok"};
let output = [];
savedData['ID'].map(function (item, index) {
let temp={};
temp['ID'] = item;
temp['comman'] = 'ok';
output.push(temp)
});
console.log(output)
Hi I have got a data in LocalStorage as JSON string:
[
{"Date":"28/04/2016","Time":"08:00","Title":"Title 1"},
{"Date":"28/04/2016","Time":"08:30","Title":"Title 2"}
]
And my module.factory looks like:
module.factory('$schedule', function() {
var schedule = {};
var result = JSON.parse(localStorage.getItem('myAgenda'));
schedule.items = [{
title: result.Title,
date: result.Date,
time: result.Time
}];
return schedule;
});
When I am trying to get data it returns undefined. When I try to get a specific object like:
console.log(result[0].Title);
It works fine and shows only the first element. I guess I missing each definition but don't know how to do it. Please help me to get all results in my schedule.items.
And I am passing the result as items into:
module.controller('ScheduleController', function($scope, $schedule) {
$scope.items = $schedule.items;
});
Many thanks.
You are trying to access fields in an array without mentioning wich array element you want to access. If you want to enumerate all agenda entries and add them to your array, it should look something like this:
module.factory('$schedule', function () {
var schedule = [];
var result = JSON.parse(localStorage.getItem('myAgenda'));
result.forEach(function (date) {
schedule.push({
title: date.Title,
date: date.Date,
time: date.Time
})
})
return schedule;
});
You should use .map over array, also add missing } in your last element of array.
var schedule = [];
//assuming result returns an array.
schedule = result.map(function(value){
return {
title: value.Title,
date: value.Date,
time: value.Time
};
})
Not familiar with module.factory, but it looks like result is an array of objects and you're accessing it like a single object when creating schedule.items.
You might have to iterate over the array and create an item per object in result.
hello I am new in node js. and i want to add a key with resultant array and print it in json array.
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
result['add_key'] = 'abcdd';
response['success'] = true;
response['result'] = result;
response['msg'] = 'Result fetched';
res.json(response);
});
It prints without add_key
The JSON array data type cannot have named keys on an array.
Normal JavaScript arrays are designed to hold data with numeric
indexes. You can stuff named keys on to them (and this can be useful
when you want to store metadata about an array which holds normal,
ordered, numerically indexed data), but that isn't what they are
designed for.
If you want named keys, use an Object, not an Array.
var test = {}; // Object
test['a'] = 'test';
test['b'] = []; // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);
While a Javascript array can have custom properties such as you are doing with this line of code:
result['add_key'] = 'abcdd';
JSON.stringify() (and consequently res.json() too) will only put actual array elements (not custom properties) in the generated JSON. So, if result is an array, that is why this property does not show in the generated JSON.
In fact, the JSON text format, only has a place for array elements in the JSON format for an array. There is no place for regular custom properties like your ['add_key] property. That property would have to be on a plain object for it to show in the JSON.
In the section 7 of the JSON specification where arrays are described,
it clearly shows that the only JSON representation for an array is the
array elements themselves (separated by commas). There is no place for a property name/value pair in the expression for an array.
You did not show exactly what you want the resulting JSON to look like, but there are several other ways you could represent the add_key property and value. You could move the property to the response object:
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
response['add_key'] = 'abcdd';
response['success'] = true;
response['result'] = result;
response['msg'] = 'Result fetched';
res.json(response);
});
You could put the result into it's own object and that object could have the add_key property on it:
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
var resultContainer = {};
resultContainer['add_key'] = 'abcdd';
resultContainer['result'] = result;
response['success'] = true;
response['result'] = resultContainer;
response['msg'] = 'Result fetched';
res.json(response);
});
FYI, you don't have to normally use the bracket syntax for setting properties. You could also do this (which many find a bit cleaner):
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
response.add_key = 'abcdd';
response.success = true;
response.result = result;
response.msg = 'Result fetched';
res.json(response);
});
The only time you have to use the bracket syntax is if the property name is in a string variable or if it contains certain characters that aren't permitted in the dot syntax. For regular alpha characters and a property name that is not in a variable, you can just use the dot syntax.
Nodejs doesn't have named indexed arrays (Associative arrays)
For the same Nodejs has Object data type use it
For your case
connection.modal.find( { 'id' : '2' }, function ( err, result ) {
var response = {};
// Converting array to object
result = Object.assign({}, result);
// Now you can add your required keys
result['add_key'] = 'abcdd';
response['success'] = true;
response['result'] = result;
response['msg'] = 'Result fetched';
// Now response will have numeric keys and your required key also
// but data type will object
res.json(response);
});
I hope this will helps
I have the follow object:
formData : {
_id: "550de8956e2d0948080e220f"
category: "Tag1"
isFeatured: "Yes"
likeCount: 557
title: "Integrating WordPress with Your Website"
}
I tried JavaScript but it returned a null value:
var arryFormData = Array.prototype.slice.call(formData)
How can I convert formData into an array of just its values, not properties?
As in ...
arryFormData = ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
or if You like to more functional code:
var arr = [];
angular.forEach(obj, function(value, key){
arr.push(value);
});
If you are using underscore.js,
_.values(formData)
// will get ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
See: here
Alternatively:
var res = [];
for (var x in formData){
formData.hasOwnProperty(x) && res.push(formData[x])
}
console.log(res);
In any event, the array elements might not be in the order that you want.
I prefer one line solution with Object.keys() and es6 syntax, until Object.values() is not here
const values = Object.keys(obj).map(it => obj[it])
or in es5
var values = Object.keys(obj).map(function(it) {
return obj[it]
})
I think there's No magic way, you just have to use a for loop:
for (var key in obj) {
values.push(obj[key])
}
To make it angular, you could use angular.forEach I guess...
This is how i have handled in Angular 5 to convert Object into Array as API gives response in JSON Object so we can convert it into array to use it.
let tmepArr = {};
Object.keys(res).forEach( key => {
tmepArr['name'] = [res[key].name];
tmepArr['id'] = [res[key].id];
});
this.marketplaceDropDown = [tmepArr];
I have an API Feed of global variables to be used throughout an application. The raw feed looks like this:
[
{
id: "1",
var: "g_crop_year",
val: "2015"
},
{
id: "2",
var: "g_season",
val: "F"
}
]
To me, that is awkward to work with throughout an application and I would prefer it look like this:
[
{ g_crop_year: "2015" },
{ g_season: "F" }
]
I tried this:
$http.get('/globals')
.success(function(globals){
var simpleGlobals = [];
for(var g=0; g<globals.length;g++){
var glo = {
globals[g].var: globals[g].val
};
simpleGlobals.push(glo);
}
$scope.globals = simpleGlobals;
});
My thoughts were to loop through the returned data, create the structure I want and push to a new array which I assign to $scope. But I am wrong. I get a blank page and an unexpected token in the globals[g].var: globals[g].val line.
This will not work as you expect:
var glo = {
globals[g].var: globals[g].val
};
They key of the glo object is attempting be the literal text globals[g].var; change that, instead, to:
var glo = {};
glo[globals[g].var] = globals[g].val;
As a side note, you may want to assign to $rootScope or a Service to make these globals available to all of your controllers.
This is not the right approach to create your designated approach.
var glo = {
globals[g].var: globals[g].val
};
The string globals[g].var is actually being considered as the key rather than interpreting it as a value.
You should instead create a blank object first and then use the array annotation to assign a particular value to the key.
var glo = {};
glo[globals[g].var] = globals[g].val;