Appending to JS object - javascript

Hope this isn't too much of a repeating question, I've checked around seen similar but can't seem to solve my issue.
I have a JS object:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {} ,
region: {}
};
I want to check if an item is in gender, if not add and set to 1 else increment into. Note that appending it in is important.
Can someone kindly tell me whats wrong:
var input = 'female'; //for purposes of this example
var processGender = function(input) {
if(option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
}else {
option1Data['gender'][input] = 1;
}
};
User.find({_id: item['userID']}, {gender: 1, country:1}, function(req, foundUser) {
processGender(foundUser[0]['gender']);
});

You can't guarantee property order if using an object, you can see this stackoverflow answer for that :
Does JavaScript Guarantee Object Property Order?
So appending is out of the question for the structure you're using.
But maybe something like below would work for you :
var maleGenderObject= { gender : "male" , count : 0 };
var femaleGenderObject = {gender : "female" , count : 0 };
var option1Data = { option: 'Yes',
numberOfPeople: 3,
gender: [] ,
region: {} };
Then when adding , you can do something like :
var input = "female";
//Nothing exists at the moment, so add the proper object, I added both since there are only two, but you can modify for more genders, but logic will be a bit more complex
if ( option1Data.gender.length == 0 ){
if (input == "female" ){
option1Data.gender.push(femaleGenderObject);
option1Data.gender.push(maleGenderObject);
}
else {
option1Data.gender.push(maleGenderObject);
option1Data.gender.push(femaleGenderObject);
}
}
//If both gender objects exist, determine which one you want, and increment its count
if (option1Data.gender[0].gender == input){
option1Data.gender[0].gender.count++;
}
else {
option1Data.gender[1].gender.count++;
}
This definitely can be optimized, but it's really two variables so I think simple straightforward is better in this case
Another way is to have your gender objects have an order property, and you can use that.

Your code is working fine:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {},
region: {}
},
input = 'female';
if (option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
} else {
option1Data['gender'][input] = 1;
}
document.write('<pre>' + JSON.stringify(option1Data, 0, 4) + '</pre>');

Related

Use variable to store "change.doc" path

I'm trying to use variable as a firestore doc path :
console.log(change.doc.data().m_1.name); <----- This work well !
a = 1;
let me = change.doc.data().m_+a; <----- But not that....
console.log(me.name);
How can i do that ?
Thank you in advance ! :)
You should use brackets when using dynamic property.
let me = change.doc.data()['m_' + a];
I think you want to build the name of the key as its own variable and use that to index into the object.
const a = 1;
const key = "m_" + a;
const me = change.doc.data()[key];
When you use your a variable in your example you're asking JS to add the number 1 to your functions output. This is not the correct way. You want to use a key to access the data from your data() functions return output as shown below.
change = {
doc: {
data: function() {
return {
m_1: {
name: "Mario",
occupation: "plumber",
siblings: 1,
age: 24
},
m_2: {
name: "Mike",
occupation: "developer",
siblings: 3,
age: "28"
}
}
}
}
}
console.log("Old way:" + change.doc.data().m_1.name);
const a = 1;
let me = change.doc.data()['m_' + a];
console.log("Desired way: " + me.name)
I have assumed a simple data structure derived from your question but I am not certain that it's what you get. But it might look a little like it.
EDIT awww.... The page didn't refresh and I did not see the two first answers :( well... at least we agree

Preventing duplicate objects from being added to array?

I am building a little shop for a client and storing the information as an array of objects. But I want to ensure that I am not creating "duplicate" objects. I have seen similar solutions, but perhaps it is my "newness" to coding preventing me from getting the gist of them to implement in my own code, so I'd like some advice specific to what I have done.
I have tried putting my code in an if look, and if no "part", my variable looking for part number, exists in the code, then add the part, and could not get it to function.
Here is the function I am working on:
function submitButton(something) {
window.scroll(0, 0);
cartData = ($(this).attr("data").split(','));
arrObj.push({
part: cartData[0],
description: cartData[1]
});
}
arrObj is defined as a global variable, and is what I am working with here, with a "part" and a "description", which is the data I am trying to save from elsewhere and output to my "#cart". I have that part working, I just want to ensure that the user cannot add the same item twice. (or more times.)
Sorry if my code is shoddy or I look ignorant; I am currently a student trying to figure these things out so most of JS and Jquery is completely new to me. Thank you.
You can create a proxy and use Map to hold and access values, something like this
let cart = new Map([{ id: 1, title: "Dog toy" }, { id: 2, title: "Best of Stackoverflow 2018" }].map(v=>[v.id,v]));
let handler = {
set: function(target,prop, value, reciver){
if(target.has(+prop)){
console.log('already available')
} else{
target.set(prop,value)
}
},
get: function(target,prop){
return target.get(prop)
}
}
let proxied = new Proxy(cart, handler)
proxied['1'] = {id:1,title:'Dog toy'}
proxied['3'] = {id:3,title:'Dog toy new value'}
console.log(proxied['3'])
Assuming the 'part' property is unique on every cartData, I did checking only based on it.
function submitButton(something) {
window.scroll(0, 0);
cartData = ($(this).attr("data").split(','));
if(!isDuplicate(cartData))
arrObj.push({
part: cartData[0],
description: cartData[1]
});
}
const isDuplicate = (arr) => {
for(obj of arrObj){
if(arr[0] === obj.part)
return true;
}
return false;
}
If you want to do the checking on both 'part' and 'description' properties, you may replace the if statement with if(arr[0] === obj.part && arr[1] === obj.description).
Thanks everyone for their suggestions. Using this and help from a friend, this is the solution that worked:
function submitButton(something) {
window.scroll(0,0);
cartData = ($(this).attr("data").split(','));
let cartObj = {
part: cartData[0],
description: cartData[1],
quantity: 1
}
match = false
arrObj.forEach(function(cartObject){
if (cartObject.part == cartData[0]) {
match = true;
}
})
console.log(arrObj);
if (!match) {
arrObj.push(cartObj);
}
Okay, you have multiple possible approaches to this. All of them need you to specify some kind of identifier on the items which the user can add. Usually, this is just an ID integer.
So, if you have that integer you can do the following check to make sure it's not in the array of objects:
let cart = [{ id: 1, title: "Dog toy" }, { id: 2, title: "Best of Stackoverflow 2018" }];
function isInCart(id) {
return cart.some(obj => obj.id === id);
}
console.log(isInCart(1));
console.log(isInCart(3));
Another approach is saving the items by their id in an object:
let cart = { 1: { title: "Dog toy" }, 2: { title: "Best of Stackoverflow 2018" } };
function isInCart(id) {
if(cart[id]) return true;
return false;
}
Try to use indexOf to check if the object exists, for example:
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('aaa'));
// expected output: -1

Create or Update cookie array in Jquery

I want to create if the value is 0 and update if the value is 1.
So I wrote this one,
var juiceCart = [{
'name': val,
'count': unTouch
}];
if (value == 0) {
console.log('create cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
} else {
console.log('update cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
}
Inside the doDummyCall()
I am just doing a ajax call to update the headers and
var cookieJuiceCart = $.parseJSON($.cookie("juiceCart"));
$.each(cookieJuiceCart, function (index, value) {
console.log('Id : ' + value.name);
console.log('Value : ' + value.count);
});
and then printing the cookie in each function to know all the items present in it.
If i add the first item, it is printing
Id : 1
Value : 1
Then, if i add the Second item it is printing
Id : 2
Value : 1
But what i expect is
Id : 1
Value : 1
Id : 2
Value : 1
I know that the old value is replaced because i am not pushing the value in it.
So, I did
juiceCart.push({'name': val, 'count': unTouch});
But it is just replacing the old value with new one.
How can i check the existence of old value inside the array and create or update according to it.
The actual problem seems to me is your array:
var juiceCart = [{
'name': val,
'count': unTouch
}];
which is using vars to update same object instead of pushing new object.
You can do this:
var juiceCart = $.parseJSON($.cookie("juiceCart")) || []; // create a blank array taken from #apokryfos's answer.
juiceCart.push({'name': val, 'count': unTouch}); // <---now push it here.
This way you are able to push new object each time you call it.
This is what I got from the question. It's a bit poorly explained so I may not have understood what you need to do.
var juiceCart = $.parseJSON($.cookie("juiceCart")) || [];
var newItem = true;
juiceCart.each(function (i, v) {
if (v.name == val) { v.count++; newItem = false; }
});
if (newItem) {
juiceCart.push({'name': val, 'count': unTouch});
}
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

How to get count of elements according to the value contained in javascript

I have a json array contains many elements. A part of the array is given:
var some_array = {
"0":{
"picture":"qwerty.jpg",
"textofPicture":"comment for Picture 5",
"picNo":1,
"id":25,
"uid0":125,
"uid1":123,
"uid2":126,
"uid3":127,
"uid4":124,
"u0":"149",
"u1":"80",
"u2":"71",
"u3":"108",
"u4":"158",
"accepted":false,
"su":"",
"point":0
},
"1":{
"picture":"qwerty.jpg",
"textofPicture":"comment for Picture 3",
"picNo":2,
"id":23,
"uid0":113,
"uid1":117,
"uid2":116,
"uid3":114,
"uid4":115,
"u0":"62",
"u1":"58",
"u2":"115",
"u3":"138",
"u4":"106",
"accepted":false,
"su":"",
"point":0
}
}
I want to count how many accepted key's value is true. I am sure there is good way to do this. I do not want to dive into loops.
One way to obtain the count you're looking for is like this
var count = 0;
var some_array = [
0 : {
accepted : false
},
1 : {
accepted : true
}
];
for (var i in some_array) {
if (some_array[i].accepted === true) {
count++;
}
}
return count;
Let me know if this helps and makes since to you. if need be i can make plunker for a visual.

Categories

Resources