Add remove filter an Array Javascript - javascript

1) I am looking for inbuilt jquery functions which would add/remove/get an item from an array.
Or a better way to do the same thing I have done below. Although below code works but I feel there should be some better way.
I am not very good at JavaScript so this code may look crappy :)
var items =
[
{"Selected": false, "Text": "FirstElement", "Value": "1"},
{"Selected": false, "Text": "SecondElement", "Value": "2"},
{"Selected": false, "Text": "ThirdElement", "Value": "3"},
{"Selected": false, "Text": "FourthElement", "Value": "4"}
]
function findItem(items, elementValue) {
var item = {};
if(elementValue == undefined || elementValue =="")
return item;
var i = $.map(items, function(n,i) { return i; }).length;
while(i--){
var temp = items[i].Value;
if(elementValue == items[i].Value){
item = {"Text": items[i].Text, "Value": items[i].Value};
}
}
return item;
}
function removeItem(items, elementValue) {
if(elementValue == undefined || elementValue =="")
return items;
var result = $.grep(items, function(e){
return e.Value != elementValue;
});
return result;
}
function addItem(items, elementValue, elementText) {
if(elementValue == undefined || elementValue =="")
return items;
var i = $.map(items, function(n,i) { return i; }).length;
var x = i;
var valueExists = false;
while(i--){
var temp = items[i].Value;
if(elementValue == items[i].Value){
valueExists = true;
}
}
if(!valueExists){
items[x] = {"Selected": false, "Value": elementValue, "Text": elementText};
}
//I also need some sorting here on Value
return items;
}
2) I am using
var tempItems = Object.assign({}, addItem(items, elementValue, elementText))
After adding an item I want the reference in a different temp object as I have to play around with master and filtered list. Is there a way I can add an item and get another instance of returned items.
Probably Object.assign is the root cause I am struggling with add/remove/get items.
Any suggestion is welcomed and appreciated. Thank You!

You can use built in javascript functions (not jquery :):
// Finding an item
items.find(function(item) { return item.Value == '3'})
// Removing/filtering out an item (returns a new copy)
items.filter(function(item) { return item.Value !== '3'})
To return a new copy of addItem, you could copy items inside the addItems function itself using Object.assign({}, ...).

You could actually use the native filter method that works on array. It would be something like this:
function findElement(items, elementValue) {
let result = items.filter(function(item) {
return item.Value === elementValue;
})
console.log(result); //should output the desired result
}

Related

JSON array filter does not apply

I am trying to filter the data from an array, but it is throwing an error saying
filter() is not function
Here is the code:
var selectedObject = [];
selectedObject= JSON.stringify(formsDataSource.data());
//console.log(selectedObject);
//var filtered = $.grep(selectedObject, function (el) {
// return el.po_order_no = 18;
//});
//console.log((filtered));
if (selectedObject == undefined) {
alert("Undefined");
} else {
var data= selectedObject.filter(function (element) { return element.po_order_no = "18"; })
alert("" + data);
}
I tried many things but it is still throwing an error. Any help?
Few observations :
selectedObject= JSON.stringify(formsDataSource.data());
This statement states that selectedObject is a string. A string does not have a filter() method.
condition inside filter function should be element.po_order_no == "18" instead of element.po_order_no = "18"
Solution :
var selectedObject = [
{
"po_order_no": 18,
"po_order_name": "abc"
},
{
"po_order_no": 19,
"po_order_name": "xyz"
}
];
if (selectedObject == undefined) {
console.log("Undefined");
} else {
var data = selectedObject.filter(element => element.po_order_no == "18")
console.log(data);
}

How to avoid reading previous JSON array value which are stored in page before page refresh

I want to avoid reading the previous objects pushed in the JSON array. As shown in the image.
I'm Self learning these concepts. so i need help, about is this the right method to add and read values.
Also i dont know how to ask this question technically. so i would appreciate if someone would tell me how this question should be asked. So that i can atleast improve it for better understanding.
JQUERY
$("#click").click(function(event)
{
event.preventDefault();
var $form = $('#myform');
var $boxes =$("input[id=myCheckboxes]:checked").length;
if($boxes==0)
{
alert("Choose atleast one Category");
}
else if($form.valid() && $boxes>0)
{
//if form is valid action is performed
var data = $( "#myform" ).serializeArray();//serialize the data
var valuesArray = $('input:checkbox:checked').map( function() {
return this.value;
}).get().join(",");
data.push({ name: 'panel', value: valuesArray});
//convert json array into object
var loginFormObject = {};
$.each(data,
function(i, v) {
loginFormObject[v.name] = v.value;
});
array.push(loginFormObject);
alert("Added Successfully");
viewFunction(array);
return false;
}
})
//view function
function viewFunction(array)
{
console.log(array);
var panel_arr = ["", "Regular", "Reduced Fee", "Limited Assurance","Court Programs"];
var ul_block = $("<ul/>");
$.each(array, function(i, data)
{
var panels = data.panel.split(",");
var uli_block = $("<ul/>");
$.each(panels, function(j, jdata)
{
var ulii_block = $("<ul/>");
$edit = $('<a/>').attr('href', 'javascript:;').addClass('btn btn-default active').attr('role', 'button').text('Edit')
.css('margin-left', 5);
$del = $('<a/>').addClass('btn btn-default active').attr('role', 'button').text('Delete')
.css('margin-left', 5);
$(ulii_block).append($("<li/>").html(data.ptitle).append($edit,$del));
$(uli_block).append($("<li/>").html('<span class="Collapsable">'+panel_arr[panels[j]]+'</span>')).append(ulii_block);
$edit.click(editFunction.bind(null, data));//bind data to function
});
$(ul_block).append($("<li/>").html('<span class="Collapsable">'+data.gpanel+'</span>').append(uli_block));
});
$("#addMember").append(ul_block);
$(".Collapsable").click(function () {
$(this).parent().children().toggle();
$(this).toggle();
});
$(".Collapsable").each(function(){
$(this).parent().children().toggle();
$(this).toggle();
});
}
i made this method to compare between 2 of my json objects:
//tempObj is old object and newObj is well your new JSON, this function returns bool
function isDifferentObj(tempObj, newObj) {
var tempObjLength = Object.keys(tempObj).length;
var newObjLength = Object.keys(newObj).length;
if (newObjLength >= tempObjLength) {
for (var key in newObj) {
if (typeof tempObj[key] != "undefined") {
if (newObj[key] != tempObj[key]) {
return true;
}
} else {
return true;
}
}
return false;
} else {
for (var key in tempObj) {
if (typeof newObj[key] != "undefined") {
if (tempObj[key] != newObj[key]) {
return true;
}
} else {
return true;
}
}
return false;
}
}
After a lot of trouble i found my problem. I was appending the result every time.
The code line which was making the trouble was this.
$("#addMember").append(ul_block);
I changed it to
$("#addMember").html(ul_block);
hence avoiding duplicates.

AngularJs - check if value exists in array object

var SelectedOptionId = 957;
$scope.array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}]
Is there a way of checking if a value exists in an that kind of array objects. I am using Angular and underscore.
I have tried all this -
if ($scope.array.indexOf(SelectedOptionId) === -1) {console.log('already exists')}
and
console.log($scope.array.hasOwnProperty(SelectedOptionId)); //returns false
and
console.log(_.has($scope.array, SelectedOptionId)); //returns false
You could use Array#some and check with in operator.
exists = $scope.array.some(function (o) {
return SelectedOptionId in o;
});
Check this
function checkExists (type) {
return $scope.array.some(function (obj) {
return obj === type;
}
}
var chkval=checkExists("your value")
Try this:
if($scope.array[SelectedOptionId] || _.includes(_.values($scope.array, SelectedOptionId))) { }
That should cover both a key and a value.
let selectedOptionId = "957";
let array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
let filtered = array.filter(function(element){
return Object.keys(element)[0] === selectedOptionId;
});
console.log(filtered);
console.log(_.some($scope.array, function(o) { return _.has(o, "957"); }));
using underscore
You can use filter for this. The following code should return you output array with matching results, if it exists, otherwise it will return an empty array :
var array = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var SelectedOptionId = 957;
var result = array.filter(
function(item) {return item[SelectedOptionId]}
)
console.log(result);
For your input it returns:
[ { '957': '1269' }, { '957': '1269' } ]
You can do it using the in operator or the hasOwnProperty function, to check for the existence of a key in an object inside the given array.
The way you've tried using hasOwnProperty function didn't work because you were checking it directly on the array instead of checking against the items in the array.
Check the below code snippet.
angular
.module('demo', [])
.controller('HomeController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [{
"957": "1269"
}, {
"958": "1265"
}, {
"956": "1259"
}, {
"957": "1269"
}, {
"947": "1267"
}];
var key = '957';
var isExists = keyExists(key, vm.items);
console.log('is ' + key + ' exists: ' + isExists);
function keyExists(key, items) {
for (var i = 0; i < items.length; i++) {
// if (key in items[i]) {
if (items[i].hasOwnProperty(key)) {
return true;
}
}
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="HomeController as home">
{{home.items | json}}
</div>
</div>
Different ways to do this :
Using Object hasOwnProperty() method.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
function checkOption(key) {
for(var i in arrayObj) {
if(arrayObj[i].hasOwnProperty(key) == true) {
return key+" exists.";
} else {
return key+" Not exists.";
}
}
};
console.log(checkOption(SelectedOptionId)); // 957 exists.
using Array filter() method.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var result = arrayObj.filter(function(elem) {
return elem[SelectedOptionId]
});
if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}
using Array some() method as suggested by Nina Scholz.
Working demo :
var SelectedOptionId = 957;
var arrayObj = [{"957":"1269"},{"958":"1265"},{"956":"1259"},{"957":"1269"},{"947":"1267"}];
var result = arrayObj.some(function (o) {
return SelectedOptionId in o;
});
if(result == '') {
console.log(SelectedOptionId+" not exists.");
} else {
console.log(SelectedOptionId+" exists.");
}

Saving nested json object path to a variable via recursion

Is there a way to save the "path" of a json object to a variable? That is, if I have something like this:
var obj = {"Mattress": {
"productDelivered": "Arranged by Retailer",
"productAge": {
"year": "0",
"month": "6"
}
}
};
How can I loop through and save each key node name to a variable? eg. (I need it in this format): Mattress[productDelivered], Mattress[productAge][year], Mattress[productAge][month]
I have got partly there in this fiddle http://jsfiddle.net/4cEwf/ but as you can see in the log, year and month don't get separated but append to the array as well. I know this is because of the looping I have going on but I'm stuck on how to progress to get the data format I require. The flow I have set up in the fiddle is emulating what I need.
Is there a way I haven't considered to do this?
Try
var obj = {
"Mattress": {
"productDelivered": "Arranged by Retailer",
"productAge": {
"year": "0",
"month": "6"
}
}
};
var array = [];
function process(obj, array, current){
var ikey, value;
for(key in obj){
if(obj.hasOwnProperty(key)){
value = obj[key];
ikey = current ? current + '[' + key + ']' : key;
if(typeof value == 'object'){
process(value, array, ikey)
} else {
array.push(ikey)
}
}
}
}
process(obj, array, '');
console.log(array)
Demo: Fiddle
var obj = {"Mattress": {
"productDelivered": "Arranged by Retailer",
"productAge": {
"year": "0",
"month": "6"
}
}
};
var Mattress = new Array();
for(var i in obj.Mattress){
if(typeof(obj.Mattress[i])==='object'){
for(var j in obj.Mattress[i]){
if(Mattress[i]!=undefined){
Mattress[i][j] = obj.Mattress[i][j];
}
else{
Mattress[i] = new Array();
Mattress[i][j] = obj.Mattress[i][j];
}
}
}
else{
Mattress[i] = obj.Mattress[i];
}
}
for(var i in Mattress){
if(typeof(Mattress[i])==='object'){
for(var j in Mattress[i]){
alert(j+":"+Mattress[i][j]);
}
}
else{
alert(i+":"+Mattress[i]);
}
}

Updating a JSON object using Javascript

How can i update the following JSON object dynamically using javascript or Jquery?
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
I would like to dynamically update the Username to 'Thomas' where the 'Id' is '3'.
How can I achieve this?
A plain JavaScript solution, assuming jsonObj already contains JSON:
Loop over it looking for the matching Id, set the corresponding Username, and break from the loop after the matched item has been modified:
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === 3) {
jsonObj[i].Username = "Thomas";
break;
}
}
Here it is on jsFiddle.
Here's the same thing wrapped in a function:
function setUsername(id, newUsername) {
for (var i = 0; i < jsonObj.length; i++) {
if (jsonObj[i].Id === id) {
jsonObj[i].Username = newUsername;
return;
}
}
}
// Call as
setUsername(3, "Thomas");
simply iterate over the list then check the properties of each object.
for (var i = 0; i < jsonObj.length; ++i) {
if (jsonObj[i]['Id'] === '3') {
jsonObj[i]['Username'] = 'Thomas';
}
}
$(document).ready(function(){
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}];
$.each(jsonObj,function(i,v){
if (v.Id == 3) {
v.Username = "Thomas";
return false;
}
});
alert("New Username: " + jsonObj[2].Username);
});
use:
var parsedobj = jQuery.parseJSON( jsonObj);
This will only be useful if you don't need the format to stay in string.
otherwise you'd have to convert this back to JSON using the JSON library.
var i = jsonObj.length;
while ( i --> 0 ) {
if ( jsonObj[i].Id === 3 ) {
jsonObj[ i ].Username = 'Thomas';
break;
}
}
Or, if the array is always ordered by the IDs:
jsonObj[ 2 ].Username = 'Thomas';
JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.
So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.
I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.
function setVal(update) {
/* Included to show an option if you care to use jQuery
var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
targetField: null, targetData: null, checkAllRows: false };
//update = $.extend({}, defaults, update); */
for (var i = 0; i < update.jsonRS.length; i++) {
if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
update.jsonRS[i][update.targetField] = update.targetData;
if (!update.checkAllRows) { return; }
}
}
}
var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Username':'Albert','FatherName':'Einstein'}]
With your data you would use like:
var update = {
jsonRS: jsonObj,
lookupField: "Id",
lookupKey: 2,
targetField: "Username",
targetData: "Thomas",
checkAllRows: false
};
setVal(update);
And Bob's your Uncle. :) [Works great]
For example I am using this technique in Basket functionality.
Let us add new Item to Basket.
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image'), "quantity":1, "discount":0, "total":$(this).attr('pr_price')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
itemCountInCart(productArray.length);
});
After adding some item to basket - generates json array like this
[
{
"id": "95",
"nameEn": "New Braslet",
"price": "8776",
"image": "1462012394815.jpeg",
"quantity": 1,
"discount": 0,
"total": "8776"
},
{
"id": "96",
"nameEn": "new braslet",
"price": "76",
"image": "1462012431497.jpeg",
"quantity": 1,
"discount": 0,
"total": "76"
},
{
"id": "97",
"nameEn": "khjk",
"price": "87",
"image": "1462012483421.jpeg",
"quantity": 1,
"discount": 0,
"total": "87"
}
]
For Removing some item from Basket.
$(document).on('click','[itemRemoveBtn]',function(){
var arrayFromLocal=localStorage.getObj('product');
findAndRemove(arrayFromLocal,"id",$(this).attr('basketproductid'));
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
//This function will remove element by specified property. In my case this is ID.
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
console.log('Removed from index is '+index+' result is '+JSON.stringify(result));
array.splice(index, 1);
}
});
}
And Finally the real answer of the question "Updating a JSON object using JS". In my example updating product quantity and total price on changing the "number" element value.
$(document).on('keyup mouseup','input[type=number]',function(){
var arrayFromLocal=localStorage.getObj('product');
setQuantityAndTotalPrice(arrayFromLocal,$(this).attr('updateItemid'),$(this).val());
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
function setQuantityAndTotalPrice(array,id,quantity) {
array.forEach(function(result, index) {
if(result.id === id) {
result.quantity=quantity;
result.total=(quantity*result.price);
}
});
}
I think this the more efficent way than for looping.
1-First find index of item.
2-Second edit exact element. (if not exist add)
Example :
let index= jsonObj.findIndex(x => x["Id"] === 3);
if (index == -1) {
// add
jsonObj.push({ id:3, .... });
} else {
// update
jsonObj[index]["Username"]="xoxo_gossip_girl"
}
var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Ray','FatherName':'Thompson'},
{'Id':'2','Quantity':'2','Done':'0','state':'todo',
'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Steve','FatherName':'Johnson'},
{'Id':'3','Quantity':'2','Done':'0','state':'todo',
'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
'Username':'Albert','FatherName':'Einstein'}];
for (var i = 0; i < jsonObj.length; ++i) {
if (jsonObj[i]['product_id'][0] === 314) {
this.onemorecartonsamenumber();
jsonObj[i]['Done'] = ""+this.quantity_done+"";
if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
console.log('both are equal');
jsonObj[i]['state'] = 'packed';
}else{
console.log('not equal');
jsonObj[i]['state'] = 'todo';
}
console.log('quantiy',jsonObj[i]['Quantity']);
console.log('done',jsonObj[i]['Done']);
}
}
console.log('final',jsonObj);
}
quantity_done: any = 0;
onemorecartonsamenumber() {
this.quantity_done += 1;
console.log(this.quantity_done + 1);
}
//update & push json value into json object
var sales1 = [];
if (jsonObj && Object.keys(jsonObj ).length != 0) {
jsonObj .map((value) => {
const check = sales1.filter(x => x.order_date === String(value.order_date).substring(0, 10))
if (check.length) {
sales1.filter(x => x.sale_price = Number(x.sale_price) + Number(value.sale_price))
} else {
let data = { "sale_price": Number(value.sale_price), "order_date": String(value.order_date).substring(0, 10) }
sales1.push(data)
}
})
}
You can easily update the username dynamically to 'Thomas' where the 'Id' is '3' using the following.
jsonObj.find(i=>i.Id===3).Username='Thomas'

Categories