Using javascript array in mongodb operator - javascript

I am trying to use javascript array in mongodb $in
It's always wrapping it with single quotes // '"Indoor","Outdoor","Both"'
I need it to work or like this -> "Indoor","Outdoor","Both"
url_parts.query.Venue ='Indoor,Outdoor,Both'
var query={};
if(url_parts.query.Venue!= undefined){
var myarr = url_parts.query.Venue.split(",");
var string='';
for (var i = 0; i < myarr.length; i++) {
string+="\""+myarr[i]+"\",";
};
string = string.substring(0, string.length - 1)
query.venues = { $in:[string]};
}
attraction.find(query).lean().exec(function(err, attrs) {....

As I said $in takes an array:
var url_parts.query.Venue ='Indoor,Outdoor,Both';
var query = {};
query.venues = url_parts.query.Venue.split(",");
So now query looks like this:
{ "venues" : { "$in" : [ "Indoor", "Outdoor", "Both" ] } }

Related

Parse JSON in children element in order

Here is the JSON example:
jsonData:
{ "Device": { "Content": { "UL": { "index0": "12", "index1": "1", .... "index31": "5", } } } }
This is what I tried, but it didn't work:
var index = [];
var jsonDoc = JSON.parse(data);
for(var i =0; i<32 ; i++)
{
var $arr = "index"+i;
index.push( jsonDoc.Device.Content.UL.$arr);
}
How can I extract the index from 1 to 31 and put it in the index array?
You can access hashes with the [] operator as well:
index.push( jsonDoc.Device.Content.UL[$arr]);
try converting JSON to array .
var o = jsonDoc.Device.Content.UL;
var arr = Object.keys(o).map(function(k) { return o[k] });
refer: Converting JSON Object into Javascript array
You can use for statement to iterate through an object's values:
var index = [];
for(var name in jsonDoc.Device.Content.UL)
{
index.push(jsonDoc.Device.Content.UL[name]));
}

Convert CSV string to an array without .split()

I am trying to come up with a function that will take any string and output an array of numbers and strings without using .split(). Below are the tests it needs to pass and a function that passes the tests currently. I am curious about how other people would solve this.
function csvParse(inputString) {
var outputArray = [];
var inputArray = inputString.split(',');
for (var i =0; i < inputArray.length; i++) {
if (!Number.isNaN(+inputArray[i])) {
outputArray.push(+inputArray[i]);
} else {
outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
}
}
return outputArray;
};
describe('CSV Parse', function() {
it('should parse a string of integers correctly', function() {
var input = '3,7,9,1,25';
var output = [ 3, 7, 9, 1, 25 ];
expect(csvParse(input)).to.deep.equal(output);
});
it('should parse a string of strings correctly', function() {
var input = '"3","7","9","1","25"';
var output = ["3", "7", "9", "1", "25"];
expect(csvParse(input)).to.deep.equal(output);
});
it('should parse a string of integers and strings correctly', function() {
var input = '1, "one", 2, "two", 3, "three"';
var output = [1, "one", 2, "two", 3, "three"];
expect(csvParse(input)).to.deep.equal(output);
});
});
Basic JS solution just replacing the split method as you asked (fiddle here)
function dumbComaSplit(inputString) {
var strArray = [];
var tmpStr = "";
for (var i = 0; i < inputString.length; i++) {
if (inputString.charAt(i) == ',') {
strArray.push(tmpStr);
tmpStr = "";
continue;
}
tmpStr += inputString.charAt(i);
}
strArray.push(tmpStr);
return strArray;
};
function csvParse(inputString) {
var outputArray = [];
var inputArray = dumbComaSplit(inputString);
for (var i =0; i < inputArray.length; i++) {
if (!Number.isNaN(+inputArray[i])) {
outputArray.push(+inputArray[i]);
} else {
outputArray.push(inputArray[i].replace(/['"]+/g,'').trim());
}
}
return outputArray;
};
If you really really want to parse CSV format without spilt, here is one way you can do it using new ECMAScript 6 Template Strings feature.
The basic is that we replace CSV , with mock ${b} expressions and convert the string to a Template String. Then evaluate it while using tag feature. This will create the array for us.
Here is the fiddle.
function csvParse(inputString) {
b = null; //dummy variable
//Prepare the notation to be a TemplateString. Use var b in a dummy expression
inputString = "`" + inputString.replace(/,/g, '${b}') + "`";
//Evaluate. Note that we use a tag function inside the evaluation to create the array
//We also pass the string as a Template String to evaluate. This is optional
fn = new Function(`function tag(inputArray) {
return inputArray;
}
return tag ${inputString} `);
//Return the array
return fn().raw;
};
console.log(csvParse("power,of,es6"));
split is the way to go. But this is the answer you are looking for.

Trying to loop through arrays containing arrays containing objects, to match data

I'm tryign to write code that will loop through an array "productsArray" and match it against my productPropertyArray to pull matching information.
however productsArray is an array in an array that contains an object with the data. My Question is how can I loop through both arrays and then return the matching data.
Current function:
var pList = productsArray
if (productPropertyArray.length === 0 || productsArray.length === 0) return [];
for (var i = 0; i < pList.length; i++) {
for (var j = 0; j < pList[i].length; j++) {
if (pList[i][j] === productPropertyArray) {
return productPropertyArray;
} else {
continue;
}
}
}
return [];
};
example of pList:
productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": 1}],
[{"sellAlone": false,"test": 1}]
];
example of productPropertyArray: (its an argument thats replaced by the following)
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
productPropertyArray is just an argument in the function which is replaced by productSKUArray The setup goes like this: function(productProperty, productPropertyArray, productsArray) {
productProperty is just a string that contains sku or productID
any ideas are appreciated. thanks.
Check this out:
http://jsfiddle.net/v9d7bjms/2/
function find() {
var productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": "00544MF24F575"}],
[{"sellAlone": false,"test": 1}]
],
pList = productsArray,
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
// All arrays matching your productsSKUArray
var findings = productsArray.filter(function (productProperty) {
// .some returns true after finding first matching element (and breaks the loop)
return productProperty.some(function (obj) {
var keys = Object.keys(obj);
// We need to get all the "values" from object so we interate over
// the keys and check if any value matches something from productSKUArray
return keys.some(function (key) {
// Check if value exists in productsSKUArray
return productSKUArray.indexOf(obj[key]) > -1;
});
});
});
return findings;
}
console.log(find());
.filter will return all arrays containing objects with values from productSKUArray.
See Array.prototype.filter, Array.prototype.some and Array.prototype.indexOf for method reference.
The inner if needs to refer to pList[i][j].
This will output [{sku: "131674"}, {sku: "84172"}].
var matchingData = [];
for(var productProperties in productsArray){
var pp = productsArray[productProperties];
for(var property in pp) {
var p = pp[property];
for(var propertyName in p){
var propertyValue = p[propertyName];
for(var i in productSKUArray){
if(propertyValue == productSKUArray[i]){
matchingData.push(p);
break;
}
}
}
}
}
but this is just the brute force solution.

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});

Javascript accessing name/value pairs

I'm getting JSON name/value pairs that looks like this:
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
But I would like to access the "name" value as the KEY, and the "value" value as the VALUE. Is there an elegant way to turn that piece of JSON into something like this?
{'parentid', 'blah'},
{'sitename', 'blah'}
Try this:
var items = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
var results = new Object();
for (var i = 0; i < items.length; i++)
{
results[items[i].Name] = items[i].Value;
}
This will result in something like:
var results = { parentid: "Blah", siteid: "Blah", sitename: "Blah" };
One way to do it.
var json = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
for ( var i = 0, l = json.length, obj; i < l; i++ )
{
obj = json[i];
json[i] = new Object();
json[i][obj.Name] = obj.Value;
}
// console.log() requires Firebug
console.log( json );
function objectflatten (array) {
var out = {}, i;
for(i = 0; i < array.length; i++) {
out[array[i].name] = array[i].value;
}
return out;
}
This is a function that will take an object in the form you presented, and output it as a "normal" object with the name values as keys, and the value values as values.
I'd recommend using the for( ... in ... ) method for this task. It'll grab the key names like you need.
var jsonObj = eval( '([{ "Name":"parentid", "Value":"blah" }])' );
for( var i = 0, assoc = {}, key; i < jsonObj.length; ++i )
{
for( key in jsonObj[ i ] ) // <-- this right here
{
assoc[ key ] = jsonObj[ i ][ key ];
}
}
and you end up with (from Firebug)
Object Name=parentid Value=blah
that can be accessed by object.key or object[ 'key' ] (in our case assoc.Name or assoc[ 'Value' ])
here's a link from Douglas Crockford from Yahoo! about using it as well - http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
I'm assuming you are using PHP, and the PHP echoes you assosiatice aray like this:
echo json_encode($result);
In your javascript, you could do this:
// Soemthing retrieves php result and puts it in `var result`.
data = eval("(" + result+ ")");
alert(data.parentid);
I'm not sure if this is what you want, but it's a solution.

Categories