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
Related
how can I use this type of chaining
let numbers = [20,17,35,4,12]
let evenSquares = numbers.filter{$0 % 2 == 0}.map{$0 * $0}
in such usecase
I have array of objects, I want to filter it by keys of external dictionary and then assign to those filtered objects value of dictionary where object id = dictionary key and then sort result object by dictionary value
here is code I have now:
let scoreDict: [String: Double]
var objects: [Object]
var filteredObjects = objects.filter { scoreDict.keys.contains.contains($0.id.uuidString.lowercased()) }
// .. and what next?
var scoresAssigned = filteredObjects.map { $0.score = scoreDict[$0.id.uuidString.lowercased()] } // This do not compile ""Cannot assign to property: '$0' is immutable"
Assuming Object is a struct, based on the error message...
This just shows that higher-order functions shouldn't be used everywhere. map transforms each element in a sequence into something else. So instead of assigning score, you need to return a new Object with its score changed.
var scoresAssigned = filteredObjects.map { $0.withScore(scoreDict[$0.id.uuidString.lowercased()]) }
withScore will look something like:
func withScore(_ score: Int) -> Object {
var copy = self
copy.score = score
return copy
}
But, if you just want to assign the score a new value, I recommend a simple for loop.
for i in 0..<filteredObjects.count {
filteredObjects[i].score = scoreDict[$0.id.uuidString.lowercased()]
}
Also note that you only need to access the dictionary once. If it's nil, the key doesn't exist.
var filteredObjects = [Object]()
for i in 0..<objects.count {
if let score = scoreDict[$0.id.uuidString.lowercased()] {
objects[i].score = score
filteredObjects.append(objects[i])
}
}
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,
};
};
I make json validation with ajv. I need to validate array of strings. I know which elements can be placed there so I make appropriate 'enum'. But in some case enum can be empty and array can be empty too. Here is simple test:
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : []
}
}
var data = [];
var Ajv = require('./ajv-4.1.1.js');
var ajv = Ajv({
allErrors : true
});
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid)
console.log(validate.errors);
As a result I get:
Error: schema is invalid:data.items.enum should NOT have less than 1 items, data.items should be array, data.items should match some schema in anyOf
I can add any fictive string to enum array but is it possible to validate this case in legal way? Adding 'minItems=0' restriction doesn't help.
Is it really json schema draft restriction that I can't use empty enum?
UPD: I expect to validate code in general case:
var array = Object.keys(someObj); // array: ["foo", "bar"]
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = ["foo"]; // valid
var data = ["bar"]; // valid
var data = ["bar","foo"]; // valid
I expect to validate code in special case:
var array = Object.keys(someObj); // array: []
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = []; // I expect to see it valid too but get error instead.
The enum keyword is required to have at least one value. The specification states ...
5.5.1.1. Valid values
The value of this keyword MUST be an array. This array MUST have at least one element. Elements in the array MUST be unique.
Elements in the array MAY be of any type, including null.
http://json-schema.org/latest/json-schema-validation.html#anchor76
This makes sense because an empty enum would mean nothing would ever validate. However, I do see how it could come in handy in your particular case. If you need to build the schema dynamically, you will need to check for the empty array case and use a different schema.
Here's one way to do it:
{
"type": "array",
"maxItems": 0
}
Here's another:
{
"type": "array",
"not": {}
}
I'm using fuzzy module with node but I have long JSON Array contain object. I need matched object whole. Like
link of module
Fuzzy Modules
var list = [
{rompalu: 'baconing', zibbity: 'simba'}
, {rompalu: 'narwhal' , zibbity: 'mufasa'}
, {rompalu: 'a mighty bear canoe', zibbity: 'saddam hussein'}
];
I have above list of JSON Array and if I pass word narwhal than It's return only matched words in Array but I need array of matched object. output like :
[
{rompalu: 'narwhal' , zibbity: 'mufasa'}
]
There seem to be various options.
Filter the list manually using fuzzy.test():
var results = list.filter(function(obj) {
return fuzzy.test('narwhal', obj.rompalu);
});
Extract the "originals":
var options = { extract: function(el) { return el.rompalu; } };
var results = fuzzy.filter('narwhal', list, options).map(function(r) {
return r.original;
});
I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});