How to check if a value exists in array with .includes? - javascript

I know we can use .includes but I've been struggling to get it to work with my array. What I want is for my function to check if the value already exists and if it does to remove it from the array.
The value is a string. That value comes from an object that has .name as a property within the object.
0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}
I mapped through the data and assigned each button with a value of {d.name}
I am using a button to get the value with this function below
and adding the values to 'favs'.
const favs = [];
function checkId(e) {
if (e.target.value !== "")
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
}
console.log
favs
[
"3-Bit-CNC-Starter-Pack",
"3-Bit-CNC-Starter-Pack"
]
How can I check to see if the value already exists within the array using .includes?

Just check before push:
function checkId(e) {
if (e.target.value !== ""
&& !favs.includes(e.target.value))
{
favs.push(e.target.value);
// other code here
}
}

["Sam", "Great", "Sample", "High"].includes("Sam"); // true
if not false

Related

javascript string comparison issue in array.filter()

I have an array which contains following objects.
myArray = [
{ item: { id: 111557 } },
{ item2: { id: 500600 } }]
and I have a variable
targetItemID = '111557'
Note that one is string, and the ones in array are numbers. I'm trying to get the object having the correct item id.
Here is what I have tried,
myArray = [
{ item: { id: 111557 } },
{ item2: { id: 500600 } }]
targetItemID = '111557'
var newArray = myArray.filter(x => {
console.log(x.item.id.toString())
console.log(targetItemID.toString())
x.item.id.toString() === itemID.toString()
})
console.log(newArray);
I expect all matching objects to be added to 'newArray'. I tried to check the values before comparison, They are both strings, they seem exactly same, but my newArray is still empty.
Your second object doesn't have an item property and should.
You need a return in your filter function.
You must compare x.item.id against targetItemID, not itemID. Since you are using console.log() you would have seen and error of itemID id not defined ;).
myArray = [
{ item: { id: 111557 } },
{ item: { id: 500600 } }
];
targetItemID = '111557'
var newArray = myArray.filter(x => {
//console.log(x.item.id.toString())
//console.log(targetItemID.toString())
return x.item.id.toString() === targetItemID.toString();
});
console.log(newArray);
There are a few issues here. First, not all your objects have an item property, so you'll need to check it exists. Second, you're comparing them against a non-existent itemID instead of targetItemID, and finally, and #bryan60 mentioned, if you open a block in an anonymous lambda, you need an explicit return statement, although, to be honest, you really don't need the block in this case:
var newArray =
myArray.filter(x => x.item && x.item.id && x.item.id.toString() === targetItemID)
you need to return for filter to work:
return x.item.id.toString() === itemID.toString();

Matching value of data object in VueJs

How can I retrieve the data from a data object in Vue?
I have data in this format:
datasets: [{
text:"Cars",
value: "[1,2,3]"
},
{
text:"Trains",
value: "[1,4,10]
}
]
Now I from route props I get the following info:
this.selectedText= this.$route.name;
Where this.$route.name is "Cars" for example.
Now I want to take this use this.selectedValue to get corresponding Value from this array:
so if this.selectedText="Cars" then this.selectedValue=[1,2,3] or based on this I want to retrieve the value of given text.
Create a method and use this code to find out the matching one.
function setSelectedValue() {
let matchingDatSet = this.datasets.find(ele => ele.text == this.selectedText);
if(matchingDataSet !== undefined) {
this.selectedValue = matchingDataSet.value;
}
}

Update values on multi level nested Object with javascript

I have an Object on sessionStorage for which I need to update values on user input. I am able to update at the root of the Object but not the values that are nested on a deeper level.
request('http://localhost:7474/graphql/', query).then(data => {...}
sessionStorage.setItem('queryData', JSON.stringify(data));
function update(value){
let prevData = JSON.parse(sessionStorage.getItem('queryData'));
Object.keys(value).forEach(function(val, key){
prevData[val] = value[val];
});
sessionStorage.setItem('queryData', JSON.stringify(prevData));
}
update({ maritalStatus: "single" });
So maritalStatus ends up been added and not replaced and I must replace the value:
Object: [,...]
0: {id: "x", maritalStatus: "married"} //want to replace this value here
maritalStatus: "single" // this is where the value is been written
Your data in storage is an Array. So the way you are updating it like prevData[val] = value[val]; is adding another property to the array with index of maritalStatus and value of "single". The object at index 0 is untouched.
My suggested fix is to also include the id in your update call. Then loop through the array in storage and look for the object with the matching id.
Once the id matches update that object, or log if no id matches are found.
let dataInStorage = [{
id: "x",
maritalStatus: "married"
}];
function update(updateObj) {
let prevData = dataInStorage;
let id = updateObj.id;
dataInStorage.forEach(function(data) {
if (data.id === id) {
Object.keys(updateObj).forEach(function(key, index) {
data[key] = updateObj[key];
});
} else {
console.log(`did not find object with id: ${id}`);
}
});
console.log(prevData)
//sessionStorage.setItem('queryData', JSON.stringify(prevData));
}
update({
id: "x",
maritalStatus: "single"
});

onChange to check all property of object exist and is not undefined or empty string

This is a very common usage where you have to check whether all fields are filled. I use react onChange and apply e.target.name as key to my object.
like I do console.log(this.state.user); I will get
user : {
name:"something",
age:1
}
but how to check if everything is not empty or null? I check manually like user.name != undefined but my key is more than 10. Is there any better lodash method to do this?
I set state like this
const user = this.state.user;
user[field] = event.target.value;
this.setState({
user
});
You can iterate the values of your object and use reduce method.
const allExist = Object.values(this.state.user)
.reduce(function(accumulator, current){
return accumulator && !!current
}, true);
const user = {
name:"something",
age:1
}
const allExist = Object.keys(user)
.reduce(function(accumulator, current){
return accumulator && !!current
}, true);
console.log(allExist);
You could use Object.keys method - loop the resulting array and check that each key has a valid value:
const user = {
name: "Tom",
age: 28,
address: null,
occupation: "Programmer",
interest: "JavaScript",
dob: undefined
}
const keys = Object.keys(user);
for (let i = 0; i < keys.length; i++) {
if (user[keys[i]] == null) {
console.log(`${keys[i]} needs a value`);
}
}

Convert objects present in an object to NULL value

I have the following object names $scope.parameters. When i execute console.log as shown below, i get this result
console.log($scope.parameters);
Result
Object { Name: "Diana", id: 234, Size: Object, Location: Object, Details: "none" }
Name: "Diana"
id: 234,
Size: Object
Location: Object
Details: "none"
As the result shows the elements Size and Location as Object, i want it to be replaced with null. Also, i want it to be dynamic. for e.g. if any of the above elements are Object, it should replace it to null automatically.
Can someone please let me know how to achieve this.
Test out each key of the object with its type if object make them null
if (Object.getPrototypeOf($scope.parameters.Size) === Object.prototype) {
// True if its object change it to null
$scope.parameters.Size = null;
} else {
// do nothing
}
Make a function which takes parameters to test it out and return.
angular.forEach($scope.parameters, function(value, key) {
if(typeof value === "object"){
console.log(key);
$scope.parameters[key] = null;
}
});

Categories