I want to get the value that holds the first child of a JSON array.
This is the array :
var sms = {
'1' : {
'address' : '+123',
'body' : 'SMS1'
},
'2' : {
'address' : '+123',
'body' : 'SMS2'
},
'3' : {
'address' : '+123',
'body' : 'SMS3'
},
'4' : {
'address' : '+123',
'body' : 'SMS4'
}
};
The reason is i want to loop in it to search a string using the first childs
value as it is above. Example sms.[0] = 1;
You can loop over the object using a using the in notation. Use hasOwnProperty to avoid getting references in the object
for (ii in sms) {
if (sms.hasOwnProperty(ii)) {
console.log(ii, sms[ii], sms[ii]['address'], sms[ii]['body']);
}
}
If you want to access the first child's value you can use
sms['1']
Which will return an object. If you want to access the values to the keys inside that object, you can use sms['1']['address'] or sms['1']['body'].
The first [] accesses the child of the first layer of JSON, and the second [<key_name>] accesses the value of the second layer of JSON, containing keys and values.
I don't know if I follow your instructions, but try this to access each element of this JSON.
for(i in sms){
console.log(sms[i]);
}
You can JSON api to parse the JSON input and fetch the respective child
JSONObject obj = new JSONObject(stringData);
JSONArray resultArr = obj.getJSONArray("sms");
JSONArray headrArr = null;
JSONObject jo = resultArr.optJSONObject(0);
if(jo != null){
headrArr = jo.names();
}
System.out.println(headrArr.get(0));
Related
I want to take each element of an array of documents I queried and check if it is in an other array of documents I queried
I have this model :
var dataTypeSchema = new Schema({
name : String,
description : String,
// Personnel || Professionel || Intime
category : String,
provenance : {
type : Schema.ObjectId,
ref : 'Service'
}
});
and this one :
var dataUseSchema = new Schema({
purpose : {
type : Schema.ObjectId,
ref : 'Purposes'
},
dataTypes : [{
type : Schema.ObjectId,
ref : 'DataType'
}],
description : String,
service : {
type : Schema.ObjectId,
ref : 'Service'
},
user : {
type : Schema.ObjectId,
ref : 'User'
}
});
I basically query an array of dataTypes and then want to check for each one if it is in a specific dataUse.data
I tried several methods of comparison : includes, indexOf, even comparing each elements _ids, it always returns false
I have checked that both arrays indeed contain documents and that they have some documents in common
Here is my code (one attempt) for comparing, I am first getting an array of DataUses and then for each one I want to check which values it shares with the dataTypesArray
const dataTypesArray = await Service.getServiceDataTypes(req.params.serviceName)
DataUse.find({service : serviceID, user : serviceID})
.populate('purpose dataTypes service user')
.exec()
.then(dataUses => {
for(let j = 0; j < dataUses.length; j++) {
for(let k = 0; k < dataTypesIDs.length; k++) {
if(dataUses[j].dataTypes.indexOf(dataTypesIDs[k])==-1) {
dataUses[j]["otherData"].push(dataTypesIDs[k])
}
}
}
return dataUseArray
})
.catch(console.log)
For the last if (condition), everything sets equal to -1
Both dataTypes arrays are populated, but as I said I tried comparing just _id and still same result
thanks !
Here is how you can do it...
To compare an array with other of Mongoose Array.
See the IDs your are getting are mongoose ObjectID which is an object
To compare an Array of ObjectID with other ObjectID:
// converting dataTypes to String,
// you can also convert it by using `lean`
// i.e Model.find().lean().exec()
// this would return JavascriptObject instead of MongooseModel
dataTypeIDs = dataTypes.map(i => i.toString()); // converting to plain
// Array of string
dataTypeIDs.indexOf(someDataTypeID.toString()); // returns -1 if not found
You can use the last line to convert it anyway you like in your if (condition)
Change this block of code like this:
.then(dataUses => {
// assuming its an Array of ObjectID
dataTypesIDsArray = dataTypesIDs.map(i => i.toString())
for(let j = 0; j < dataUses.length; j++) {
usesDataTypes = dataUses[j].dataTypes.map(i => i.toString())
for(let k = 0; k < dataTypesIDsArray.length; k++) {
if(usesDataTypes.indexOf(dataTypesIDsArray[k]) == -1) {
dataUses[j]["otherData"].push(dataTypesIDsArray[k])
// use ObjectID from mongoDB if you want to cast it to "ObjectId"
}
}
}
return dataUseArray;
})
Its not tested, but I have taken reference of an existing tested code from my project.
Here I have this json file.
{
"BnUs5hQZkJWLU9jGlpx9Ifq5ocf2" : {
"bio" : "Your bio!\r",
"birthday" : "Date of Birth?",
"location" : "Location?",
"markerBorder" : 1.5542403222038021E7,
"markerColor" : 8222122.31461079,
"name" : "NamesName?",
"profilePrivacy" : 2,
"sex" : "Gender?",
"privacy" : 2,
"points" : {
"-Kc7lfJk3XbPlNyk-wIR" : {
"address" : "dsfsdfasfsfd",
"description" : "status/desription",
"latitude" : 35.2,
"longitude" : -80.7,
"mediaTargets" : "none",
"pub" : false,
"timestamp" : 1486205926658
},
"aaa" : "aaa"
}
}
}
Those random string of charactors are automatically made when I use firebase.
In this scenario, there might be more "points" I will have to take account for. So when I reference points, I should be talking to an array since it contains both "-Kc7lfJk3XbPlNyk-wIR" (an array) and "aaa" (a string).
So why do I get a type error when trying to convert parsedObject.points into an array?
var parsedObject:Object = JSON.parse(e.target.data);
var multiArray:Array = parsedObject.points;
TypeError: Error #1034: Type Coercion failed: cannot convert Object#5c16089 to Array.
I'm basically trying to do the opposite of what this guy is doing.
Edit: I see in the notes that it only handles string, numbers and Boolean values..
I managed to work around it by adding a "parent" node in the object that duplicates the same value as the name of the entire node so I can reference it in the script. Is there a better way to go about this? Seems pretty redundant.
var parsedObject:Object = JSON.parse(e.target.data);
var myPoints:Object = parsedObject["points"];
//Get all trek names
for each (var key:Object in myPoints)
{
trace("Key = " + key.parent);
trace(parsedObject.treks[key.parent].latitude) //Returns -80.7
}
Because Array is a subclass of Object.
var A:Array = new Array();
var B:Object = new Object();
trace(A is Array); // true
trace(A is Object); // true
trace(B is Array); // false
trace(B is Object); // true
B = new Array(); // nothing wrong here
A = new Object(); // throws exception
So, you might want to tell what kind of data you want to obtain in the Array form from the parsedObject.points Object to proceed.
Alternately, that is how you get actual Array from JSON string:
{
"list": [1,2,3,4,5,6]
}
Looks like it's correctly being parsed by JSON.parse to me.
Arrays in JSON use square brackets, braces are interpreted as objects.
You'd only expect an Array from JSON.parse if you had
"points": [
...
]
whereas this is an Object:
"points": {
...
}
I suggest you look into why you aren't getting [] from your source.
I had an an object
{
sampletrue:{
data1:'data',
data2:'data'
},
samplefalse:{
data1:'data',
data2:'data'
}
}
Here, what i'm trying to do is with the object key name, i want to add a new key/value pair into it. Let's say for 'sampletrue' object i want to match the key name and if it has 'true' i need to add a new value as "resolve:'enable'" and if it is 'false' i want to add "resolve:'disable'" I'm using lodash in my code.
Sample Output:
{
sampletrue:{
data1:'data',
data2:'data',
resolve:'enable'
},
samplefalse:{
data1:'data',
data2:'data'
resolve:'disable'
}
}
Thanks!
you can find explanation in comments:
var d = {
sampletrue: {
data1: 'data',
data2: 'data'
},
samplefalse: {
data1: 'data',
data2: 'data'
}
}
// loop through the keys of the object with Object.keys() and forEach()
Object.keys(d).forEach(k => {
// we check with match method if the key (k) matches 'true'
if (k.match(/true$/))
d[k].resolve='enable' ;//if it matches assign resolve prop , 'enable' val
//same as above but with 'false'
if (k.match(/false$/))
d[k].resolve='disable' ;
})
console.log(d)
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 am trying to separate out the city and state from the location array object from Facebook in Laravel. Before when I did this, I simply tried something similar to what I am trying in my Oauth2 Controller:
$citystate = $user['location'];
$citystate2 = $citystate['name'];
$split = explode(", ", $citystate2);
$city = $split[0];
$state = $split[1];
In the provider file, Facebook.php, I have this:
'location' => $user->location
However, when I run this, I get the error:
Use of undefined constant name - assumed 'name'
So, my question is, how do I access the "name" portion of the location array object. Thank you for your help!
At first, you should json_decode (if it's a json string) like
$userArray = json_decode($user, true);
So, you can use it like an array
$citystate = $userArray['location'];
Also you can check if the $user is already an array or not using
if(is_array($user) && array_key_exists('location', $user)) {
// ...
$citystate = $user['location'];
// ...
}
Then you'll get an array like this
array (size=2)
'id' => string 'xxx' (length=15) // xxx = digits
'name' => string 'Sylhet' (length=6)
Update : $user['location'] is an object :
object(stdClass)#180 (2) { ["id"]=> string(15) "114952118516947" ["name"]=> string(25) "San Francisco, California" }
So, it should be :
$citystate = $user['location'];
$citystate->name;