How to convert an array to Collection in backbone - javascript

I have an array defined as:
this.noOfHouseHold = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];
I'm trying to convert it to a Backbone Collection as:
var adultListCollection = new Backbone.Collection(this.noOfHouseHold);
It gives me the list but for 2 digit numbers, it shows something like this:
attributes: Object
0: "1"
1: "1"
I'm not able to understand as to what is wrong here or is it the wrong way I'm converting my array to collections. Please suggest. Thanks in advance!

A Backbone collection expects a list of models/hashes of attributes that can be converted to a model but you have a plain array.
You will have to transform your array to a list of hashes. Assuming your values are the ids of your models :
var lst = _.map(this.noOfHouseHold, function(val) {
return {id: val};
});
var adultListCollection = new Backbone.Collection(lst);

Backbone.Collection expects a list of models or objects (because they can be converted to Backbone.Model). In order to persist the array you have to convert those primitives into objects. Use Backbone.Collection.parse and _.map to turn your array of primitives into an array of objects:
var AdultListCollection = Backbone.Collection.extend({
parse: function (noOfHouseHold) {
var res = _.map(noOfHouseHold, function (n) {
return {id: n};
});
return res;
}
});
Now you can instantiate your Collection with an array:
var adultListCollection = new AdultListCollection(this.noOfHouseHold, {parse: true});
Example: JSFiddle

Related

Filter object properties based on array of keywords

Looking for a way to get only the objects in the 'test' object that contain either one of the 'asSrcElementsTypes' values
What is the best way to map over the array to check if they are any of those values? I keep getting errors with the below code when I try to map the array to see if it matches the key in the test object.
var asSrcElementsTypes = ['-input', '-src'];
var test = { "exitUrl":"googl.com", "otherData1":"otherData1" "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"};
const allButMe = data.filter(function(value, key){ if(key.indexOf.indexOf(asSrcElementsTypes.map()) !== -1){return key}});
Do you mean something, like that?
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object.fromEntries(
Object
.entries(test)
.filter(([key,value]) =>
asSrcElementsTypes
.some(type =>
key.includes(type)))
)
console.log(result)
.as-console-wrapper{min-height:100%;}
Or, maybe, alternative .reduce()-based way:
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object
.keys(test)
.reduce((r,key) => (
asSrcElementsTypes.some(type =>
key.includes(type)) &&
(r[key]=test[key]), r), {})
console.log(result)
.as-console-wrapper{min-height:100%;}

Remove specific properties from Array objects in Node.js

For example I have this array, if I stringfy it it would be like this:
[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
How can I do for remove from the 2 cars: the doors and price. And only leave in the array "car" and "id"? For example:
[{"car":"Toyota","ID":"1"},{"car":"Chevrolet","ID":"2"}]
Thank you!
let arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
let arr1 = arr.map(({car, ID}) => ({car, ID}));
let arr2 = arr.map(({Doors, price, ...remainingAttrs}) => remainingAttrs);
console.log('arr1:', arr1);
console.log('arr2:', arr2);
With ES6 syntax, you can deconstruct each object to create new one without writing a loop.
In your case, total number of fields remaining is same as the total number of deleted
Following are the two approaches:
If less number of fields are to be preserved, then you can go with:
const arr1 = arr.map(({car, ID}) => ({car, ID}))
If less number of fields are to be removed, then you can go with:
const arr2 = arr.map(({Doors, price, ...remainingAttrs}) =>
remainingAttrs)
You can use Array.prototype.map() to customise your result array, taking a callback function as parameter which returns a new customised object, having only car and ID properties, in each iteration.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
This is how should be your code:
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
Demo:
var arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
console.log(JSON.stringify(results));
Adding to all other answers
Cleaner approach using ES6 syntax
var originalArray =[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var immutableArray = originalArray.map(({Doors, price, ...rest})=> rest);
console.log(immutableArray);
You must iterate over your array deleting the property on each object.
Example:
for (var i = 0; i < myArray.length; i++){
delete myArray[i].myProperty
}
Adding to the answers, with ES6 and to avoid mutation and some ESlint issues.
const Array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},
{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
const newArray = Array.map((object) => {
const {car, ID} = object;
return {car, ID};
});
Check comment for explanation:
var array=[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var resultArr = array.map(function(obj){
//we take only key-value pairs we need using JS bracket notation
return {"car":obj["car"],"ID":obj["ID"]};
});
console.log(resultArr);
You would be looking for the delete operator to fully remove those properties. It could look something like this:
var array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
for (car of array) {
delete(car.Doors);
delete(car.price);
}
You could also look into using Array.splice() for faster performance on large arrays.

Javascript - how to pick random elements from an array in order?

I have an array
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
and trying to get random items from it, so:
console.log(_.sample(numbers, 5));
this will give me 5 random numbers (strings) from the array in a random order, like:
"17", "2", "3", "18", "10"
How do I get a sorted list or random items, like?
"2", "3", "10", "17", "18"
_.sample will probably not be the best choice here. I am trying to get random items from a given array and have these items picked up from left to right of the array.
How to do this in javascritp?
Thank you.
EDIT: I have an array of strings, not numbers, so I cannot sort the randomly picked items.
EDIT2: To avoid confusing, in the array are words (= strings), I used there numbers as strings to more easily demonstrate what I am trying to achieve. (sorry for possible confusions)
You can use Array.prototype.sort to sort the returned array:
ie.
_.sample(numbers, 5).sort(function(a, b) { return parseInt(a, 10) - parseInt(b, 10) })
A better random would be:
var randomChoice = numbers[~~(Math.random() * numbers.length)]
Note: the ~~ performs the same action as Math.floor() in this context. They can be interchanged.
All together:
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
var randomSample = []
for(var i=0; i < 5; i++) {
var randomChoice = numbers[~~(Math.random() * numbers.length)]
randomSample.push(randomChoice)
}
var sortedRandomSample = randomSample.sort(function(a, b) { return parseInt(a, 10) - parseInt(b, 10) })
Demo: https://jsbin.com/zosizefaga/edit?html,js,console,output
Here is a solution that doesn't make any assumption about the original order. The idea is to lookup the element's position in the original array and sort by that. However, that assumes that every element is unique.
sample.sort(function(a, b) {
return numbers.indexOf(a) - numbers.indexOf(b);
});
This will also be quite slow for large arrays.
Why don't you implement your own method of sample and after calling _.sample you call the method sort?
The easiest method I can think of is as follows:
var randomSample = _.sample(numbers.map(function(v,i){ return i; }), 5)
.sort(function(a,b){ return a-b; })
.map(function(v){ return numbers[v]; });
That is, make a temporary array that holds the indices of the original array, i.e., just the numbers 0 through numbers.length - 1):
var indices = numbers.map(function(v,i){ return i; })
Take a random sample from that array:
var sampleIndices = _.sample(indices, 5)
Sort the sample:
sampleIndices.sort(function(a,b){ return a-b; })
Then use the sorted, randomly selected indices to get values out of the original array:
var randomSample = sampleIndices.map(function(v){ return numbers[v]; });
And as shown at the beginning of my answer, you can do it all in one line without using the indices and sampleIndices variables. Although if you are going to be regularly taking samples from the same numbers array it would probably make sense to keep the indices variable to save rebuilding it every time, especially if the original array is quite large.
This will work regardless of what type of values are in the original array, because those values are just selected out at the end once random indices have been selected.
Try this:
function random(array, elements) {
return array.concat().sort(function() {
if (Math.random() < 0.5) {
return -1;
} else {
return 1;
}
}).slice(0, elements).sort(
function(a, b) {
return a - b
});
}
Here's the fiddle:
JSFiddle
This is a proposal without sorting and uses an helper array random for the selected items.
First get an empty array, then fill with true until count elements are filled and the filter the original array with the random selected positions.
This solution works for any content of the given array, without sort or lookup with indexOf.
function getSortedRandom(array, count) {
var random = array.map(function () { return false; }),
r;
while (count) {
r = Math.floor(Math.random() * array.length);
if (!random[r]) {
random[r] = true;
count--;
}
}
return array.filter(function (_, i) {
return random[i];
});
}
var random = getSortedRandom(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"], 5);
document.write('<pre>' + JSON.stringify(random, 0, 4) + '</pre>');
As of lodash 4.0.0, you can use the _.sampleSize function in conjunction with sort:
var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];
var randomSample = _.sampleSize(numbers, 5).sort();
console.log(randomSample);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>

Parsing JSON array created from PHP array

{
"3": {
"id": "3",
"ocena_ocena": "2",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "31.12.2015."
},
"1": {
"id": "1",
"ocena_ocena": "5",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "22.12.2015."
}
}
I am using ajax to get this JSON. I tried parsing it like this:
request.done(function(response) {
alert(response.ocena_ocena);
});
Could someone please help me with this?
I also need to know how can I do a foreach statement with json?
Since your JSON represents a JavaScript object, you should include the attribute name (if we consider JavaScript object to be a map, then, we need to use the key).
Try
response["1"].ocena_ocena
or
response["3"].ocena_ocena
Since you are returning a JSON object from server instead of an array, to iterate over its properties, you could do
for (var i in response) {
console.log(response[i].ocena_ocena);
}
or
Object.keys(response).forEach(function f(e) {console.log(response[e].ocena_ocena)})
If you could modify your server side code to return JSON that looks like this,
[
{
"id": "3",
"ocena_ocena": "2",
...
},
{
"id": "1",
"ocena_ocena": "5",
...
}
]
then you could iterate over it more easily
response.forEach(function f(e) {console.log(e.ocena_ocena)})

Get and store multidimensional array not JSON in Firebase

I am using multidimensional array (not JSON) in Javascript.
var Ar = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
To send or store Array Ar to Firebase Cloud I use:
var data = new Firebase("xxxx.firebaseIO.com");
data.set(Ar);
I use this 2D array form a lot.
What option do I have to get or store individual data or array back from Firebase Cloud?
Like refresh and sync Array Ar with the Cloud
Store new data the cloud Ar[2][3] = "New Text"
Get value from the cloud var x = Ar[2][3]
Hope you can help
Thanks K
var array = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
var ref = new Firebase('https://xxxx.firebaseio.com/');
ref.set(array);
ref.on('value', function(snapshot) {
var value = snapshot.val();
console.log(value);
console.log(value[2][3]);
});
The output from the above is:
[["1", "2013", "A", "Name1", "1", "1", "3", "3", "1", "2", "3", "4", ""],
["2", "2014", "B", "Name2", "1", "2", "3", "1", "1", "2", "3", "5", ""],
["3", "2015", "C", "Name3", "1", "2", "4", "4", "1", "2", "5", "4", ""]]
"Name3"
Any time any part of the array changes, the value event will fire again and the on('value' callback will be invoked.
If you want to update the array, you have two options.
array[2][3] = "New Text";
ref.set(array);
This will send the entire array to Firebase. The alternative is to update the one the element at [2][3] straight in your database:
ref.child(2).child(3).set("Newest Text");
No matter which of the two approaches you use, the on('value' callback will be invoked again.
Check out this jsbin for a working version of the code: http://jsbin.com/nawatetuya/edit?js,console
This can be answered in the Angular Firebase API docs if you're using Angular.
Look for $save and $add to save and add data to Firebase. To get values from the database, you just have to assign a variable like
var obj = $firebaseObject(ref);
and you can get the data from the variable to the DOM like
$scope.data = obj;
Pretty simple.
You can manipulate the data before it reaches the DOM inside a factory or service first then use a controller to get or present information.

Categories