Check if key exist - javascript

I have groupedTags and I need to add fields to it and add new tags across field.:
let groupedTags = {
'other': {}
}
if (!groupedTags.other[field]) {
groupedTags.other[field] = [];
}
groupedTags.other[field].push(tag);
I understand that it is necessary to initialize a new field to push new tag - Is there a more beautiful way to check if a field exists every time? I mean avoid explicit check. or is there nothing terrible about this check? there are just a lot of places where it can be repeated

Maybe you should investigate using Proxies for achieving your desired result.
Here's short example of doing so CodeSandbox -example
1) Create proxy handler to customise Object behaviour
const handler = {
set: function(obj, key, value) {
if (!obj[key]) {
obj[key] = [];
}
obj[key].push(value);
return true;
}
};
2) Assign Proxy to your Object
let groupedTags = {
other: new Proxy({}, handler)
};
Now assigning new value will go trough Proxy
groupedTags.other.b = "bar";
// {"other":{"b":["bar"]}}

If you want to create an array of elements on an empty (or not) object, you can try this. So you don't have to check if the property you want to push your element(s) already exists.
If it doesn't it will concat with an empty array, giving you an array with the one element, otherwise the value will be added to that array. Hope this helps.
const o = {};
const toAdd = [1,2,3,4];
toAdd.forEach((v) => {
o.other = (o.other || []).concat(v);
});
o.other2 = (o.other2 || []).concat(123);
console.log(o);

I believe there is no way around checking for a value + if needed initalizing it, other than doing it yourself explicitly.
You can take out one occurrence of groupedTags.other[field] using || like this:
let field = "foo", tag = "bar";
let groupedTags = {
'other': {}
}
// Get the existing items, or assign a new list & use it:
var items = groupedTags.other[field] || (groupedTags.other[field] = []);
items.push(tag);
console.log(groupedTags);
You could also make use of a helper method that encapsulates the check-and-init part:
let groupedTags = {
'other': {}
}
AddTag(groupedTags.other, "foo1", "bar1");
AddTag(groupedTags.other, "foo2", "bar2a");
AddTag(groupedTags.other, "foo2", "bar2b");
console.log(groupedTags);
// Can put this in a library.js
function AddTag(obj, field, tag) {
var items = obj[field] || (obj[field] = []);
items.push(tag);
}

Related

Insert element inside array

I have a function
checkName(output) {
output.filter((NewData) => {
return this.props.elements.filter((OldData) => {
if (NewData.key == OldData.key) {
NewData.name = OldData.name,
//there i need to add another element
// Need to add newData.number = OldData.number
}
return NewData
})
})
return output
}
and I call this function like:
const named = this.checkName(product.rows)
Now I need to add to my product's array that I passed to checkName the value "OldData.Number" to "newData.Number" that is not defined in product (so I need to create this field)
For example:
Product before the checkName function
product.rows = [NewData.name]
Product after the checkName function
product.rows = [NewData.name="value of OldData.name", NewData.number="value of OldData.number"]
How can I obtain this result?
There are 2 confusing things in your code:
You are using filter to execute an action in each member of the output array. However, filter should be used to... well, filter that array, meaning that is should not modify it, just return a sub-set of it. Instead, you might want to use forEach. However, taking into accound the next bullet, probably you want to use map.
You are modifying the array passed to the checkName function. This is confusing and can lead to hard-to-find bugs. Instead, make your function "pure", meaning that it should not mutate its inputs, instead just return the data you need from it.
I would suggest some implementation like this one:
checkName(output){
return output.map((NewData) => {
// find the old data item corresponding to the current NewData
const OldData = this.props.elements.find(x => x.key === NewData.key);
if (OldData) {
// If found, return a clone of the new data with the old data name
// This uses the spread syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
return {
...NewData, // Clone the NewData object
name: OldData.name, // set the value found in OldData.name in the "name" field of the cloned object
number: OldData.number, // You can do the same for each field for which you want to replace the value cloned from NewValue
};
} else {
// Otherwise, just return a clone of the NewData
return { ...NewData };
}
}
}
The usage would be like this:
const named = this.checkName(product.rows)
Be aware that the product.rows array won't be modified!
You can get keys and values of the old object.
const keys = Object.keys(oldObject);
const values = Object.values(oldObject);
// or
const [keys, values] = Object.entries(oldObject);
After, you will create a loop with all keys of oldObject, and insert in newObject like a array.
keys.forEach( (key, index) => newObject[key] = values[index]);
// or
for (const [key, value] of Object.entries(object1)) {
newObject[key] = value
}
Use map like this.
checkName(output){
return output.map(( NewData) =>{
this.props.elements.forEach((OldData) => {
if (NewData.key == OldData.key) {
NewData.name = OldData.name;
NewData.number = OldData.number;
}
})
return NewData;
})
// return output;
}

How to prevent object to add duplicate value and stop excuting function

Hey guys i am adding data to the array as object but i wanted to if there is any duplicate item code so its stop excuting the function and return and if the the condition is true so its take the constructor value and add itno the data structure
This what i try to prevent it from adding the value but its not work as i want
function getNo(b){
for (const [key, value] of Object.entries(data)) {
let val = value.itemCode;
if(b === val){
alert('Its equalt to item code');
break;}else{ return b;};
}}
----What i want is-----
1) Check if value is duplicate or not from the itemCode constructor
2)If its a duplicate value so its should show and alert and stop excuting the function
3)And add this function into the addItem function to check its duplicate or not
4)I store value in the data array
var item = function(name,itemCode,stock){
this.name = name;
this.itemCode = itemCode;
this.stock = stock;
}
var data = [];
function addItem(name,itemCode,stock){
var Newitem = new item(name,itemCode,stock);
data.push(Newitem);
}
addItem('BlueTee',100,50);
addItem('Yellow tee',101,100);
addItem('BrownTee',102,120);
There are multiple ways to handle this. Your choice should depend on other use cases.
The easiest way is to define data as a javascript object instead of an array. This would require keys for each object. This would look like this:
var data = {};
function addItem(name, itemCode, stock){
var newItem = new item(name, itemCode, stock);
if(data[itemCode] === undefined)
data[itemCode] = newItem;
}
If you are going to later access data as an array, then you can instead iterate over the array for each insertion. This would look like this:
function addItem(name, itemCode, stock){
var newItem = new item(name, itemCode, stock);
if(!data.some(function(x => x.itemCode === itemCode)){
data.push(newItem);
}
}
This would be slower than a normal insertion especially for large datasets. If you are going to use a very large dataset and need to be able to access as an array, then I would use a hybrid between the two. The javascript object would be used for direct access to the object. A class-like implementation would be preferred for that, but without using oo, the code would look something like this:
var data = [];
var keys = {};
function addItem(name, itemCode, stock){
var newItem = new item(name, itemCode, stock);
if(keys[itemCode] === undefined){
data.push(newItem);
keys[itemCode] = data.length - 1;
}
}
This implementation also gets complicated if you are going to modify the array more than just adding elements
You can map the data array to itemCodes and see if it includes the itemCode of the new item, and if so return an empty object for your constructor. Then in your addItem function you can choose not to add the object to the array if the object is empty.
var item = function(name,itemCode,stock){
if (data.map(i => i.itemCode).includes(itemCode)) {
alert("This item has a duplicate itemCode");
return this;
}
this.name = name;
this.itemCode = itemCode;
this.stock = stock;
}
var data = [];
function addItem(name,itemCode,stock){
var Newitem = new item(name,itemCode,stock);
if (Newitem.name) data.push(Newitem); // check if an object was created with properties
}
addItem('BlueTee',100,50);
addItem('Yellow tee',101,100);
addItem('BrownTee',102,120);
addItem('RedTee',100,70); // this won't be added because of duplicate itemCode
console.log(data); // only contains BlueTee, Yellow tee, and BrownTee objects

Check if array of objects has changed

I have an array that could contain objects. Objects can either be added to it or have a property modified. I want to check if the array has changed at all (could be element(s) added or simply just have one object have a key changed), and then update the DB based on the potential change.
Just wanna know if what I have will cover all cases and/or if there is a better way to do it.
const origArrayCopy = JSON.stringify(origArray);
someFnThatPotentiallyChanges(origArray);
if (origArrayCopy !== JSON.stringify(origArray)) {
updateDB(arr);
} else {
console.log('NO DIFF');
}
And here's a jsFiddle I created to test around with https://jsfiddle.net/j4eqwmp6/
Converting the object to a string using stringify should account for deep-nested changes, right? Any insights on this implementation and is there now a more appropriate way to do it?
Using JSON.stringify is certainly a possibility.
An alternative, is to wrap the object (array) in a proxy, and do that for every nested object as well. Then trap all actions that mutate those objects.
Here is how that could look:
function monitor(obj, cb) {
if (Object(obj) !== obj) return obj;
for (let key of Object.keys(obj)) {
obj[key] = monitor(obj[key], cb);
}
return new Proxy(obj, {
defineProperty(...args) {
cb();
return Reflect.defineProperty(...args);
},
deleteProperty(...args) {
cb();
return Reflect.deleteProperty(...args);
},
set(...args) {
cb();
return Reflect.set(...args);
}
});
};
// Example array
let origArray = [{x: 1}, { child: { y: 1} }];
// Activate the proxy:
let dirty = false;
origArray = monitor(origArray, () => dirty = true);
// Perform a mutation
origArray[1].child.y++;
console.log(dirty); // true
console.log(origArray);

Editing a jagged array in Javascript

I wish to simulate a taskbar (of running tasks/apps). I plan to store tasks something like this:
(function ()
{
var tasks = [];
addTask = function (taskName, taskWindow)
{
if (!tasks[taskName]) { tasks[taskName] = []; }
tasks[taskName].push({ taskWindow: taskWindow, taskName: taskName});
};
removeTask = function (taskName, taskWindow)
{
if (tasks[taskName])
{
//Somehow remove the object from the array
}
};
}());
How should I write removeTask() to remove the correct element from this jagged array?
I suggest using object to store your tasks, because it will make your ( specific to your requirement, I am not talking about Array vs Object) code cleaner and easier to maintain
var taskManager = (function(){
function taskManager(tasks){
// Do your tasks validation before passing to this.
var this.tasks = tasks || {}; // tasks value is not private here
}
// Assuming taskID would be unique value
taskManager.prototype.addTask = function (taskName, taskID){
if ( !this.tasks[taskID] ) {
this.tasks[taskID] = { taskID: taskID, taskName: taskName };
}
};
taskManager.prototype.removeTask = function (taskName, taskID){
if (this.tasks[taskID]){
delete this.tasks[taskID];
}
};
return taskManager;
})();
Usage:
var taskManager1 = new taskManager();
taskManager1.addTask(a,b);
taskManager1.removeTask(a);
Arrays are meant to have numeric indexes and you can use .splice() to remove a numeric indexed item from an array. Non-numeric indexes aren't really in the array, they end up just being properties on the array object and they can be removed with the delete operator.
If you don't have numeric indexes, then you should be using an object and use a property to index each item. When doing it that way, you can use delete tasks[taskName] to remove a property from the object.

Javascript: Getting the newest array

I've been thinking about how to display the newest array (because the array list would update from time to time.). I think there's a default function to it but I can't find it. Anyone knows it?
var bgImg = new Array();
bgImg[0] = "background.jpg";
bgImg[1] = "background2.jpg";
bgImg[2] = "background3.jpg";
bgImg[3] = "background4.jpg";
If you want the last element of the array,
>>> a = ['background1','background2'];
["background1", "background2"]
>>> b = a[a.length-1]
"background2"
You shouldn't need to manually assign indexes. Just do bgImg.push('background2.jpg'), and it will mutate the array for you. In your case the syntax would be...
var last = bgImg[bgImg.length-1]
If you want the newest then you need to make a variable and set it with whatever you update when you push the newest one, if it doesn't become the last one.
You could create a little object to handle this for you.
function creatImageState() {
var images = [];
return {
get latest() {
return images[images.length - 1];
},
set latest (value) {
images.push(value);
}
};
}
var s = creatImageState();
s.latest = "a.png";
s.latest = "b.png";
alert(s.latest);
IE doesn't support getters and setters so you probably need to use this.
function creatImageState() {
var images = [];
return {
getLatest : function() {
return images[images.length - 1]
},
setLatest : function(value) {
images.push(value);
}
};
}
var s = creatImageState();
s.setLatest("a.png");
s.setLatest("b.png");
alert(s.getLatest());

Categories

Resources