assigning new value to an object in object array in jquery - javascript

I have an array of objects
object will be in below format
var newUserDetail={"Age":"21","name":"Vicky","UserId":"198303"};
Now I am trying to compare UserId and replace the values
//usersList contains array of newUserDetail kind of objects
jQuery(usersList).each(function(){
if(this.UserId==newUserDetail.UserId){
this=newUserDetail;
}
});
But it throws an error
Invalid left-hand side in assignment

Set the array entry:
jQuery(usersList).each(function (i) {
if (this.UserId == newUserDetail.UserId) {
usersList[i] = newUserDetail;
return false; //if you want to break the loop
}
});

Try this
$(document).ready(function() {
var newUserDetail = {
"Age": "21",
"name": "Vicky",
"UserId": "198303"
};
var tm = {
"Age": "21",
"name": "Vicky",
"UserId": "198303"
};
$.each(newUserDetail, function(k, i) {
if (i == tm.UserId) {
alert("User ID match");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Map function in JSON array

I want to find an object from a JSON array. My code is working fine with the object found. But the issue is what if the employee id is not? My code console's "not found" two times. Kindly guide me on what the issue is with my code.
var E_ID
let empArray = [
{
"employee": {
"employee_ID": 16,
"employee_designation": "Node.js",
"employee_FirstName": "John",
"employee_lastName": "Doe",
}
},
{
"employee": {
"employee_ID": 17,
"employee_designation": "Full Stack",
"employee_FirstName": "Samual",
"employee_lastName": "Smith",
},
}
]
function search_EmployeeByID(E_ID) {
empArray.map(item => {
if (item.employee.employee_ID == E_ID) {
console.log(item.employee)
return true
}else {
console.log("not found")
return false
}
})
}
E_ID = parseInt(prompt("Enter Employee_ID to search for:"))
search_EmployeeByID(E_ID);`
The if statement should not be inside find(). find() will return the matching element, or null if it's not found. So test the return value.
function searchEmployeeByID(e_id) {
let emp = empArray.find(e => e.employee.employee_ID == e_id);
if (emp) (
console.log(emp.employee);
return true;
} else {
console.log("not found");
return false;
}
}

How to create new object with limited data from other object in Vue JS

I am trying to create a search app that looks for products. I’ve got a PHP script that returns results in JSON format when a keyword is posted to it. I post to there with axios.
Now if there are 40 results for example the dropdown of results will be too long. So I want to create a new object from the object of 40 results and limit this object to 6.
I tried this by creating a function inside computed like this:
Object(this.responseData) is my full object with all results from my PHP script in a JSON object.
filteredData is my new object that I added in my data.
test(){
var fullResults = Object(this.responseData);
var number = 0;
for (var key in fullResults) {
number++;
if(!number > 6){
this.filteredData[number] += fullResults[key]
}
}
console.log(this.filteredData)
},
But my log just shows: Proxy {}. What am I doing wrong? I need to get all results from the old object, and add them to a new empty object with a limit of 6.
This is my full JS:
let app = Vue.createApp({
data: function(){
return{
// Object to fill with JSON response
responseData:{},
// Object to fill with filtered result (max 6)
filteredData: {},
showResultDiv: false,
totalResults: 0
}
},
methods:{
// Function to show loading dots until json returned
loadDiv(condition, content){
this.showResultDiv = condition
},
async fetchResults(){
await axios.post('includes/searchproducts_json.php', {
// Post data, add value of input to searchterm
searchterm: this.$refs.searchterm.value
})
.then((response)=>{
this.responseData = response.data
// Get length of returned object and add to totalResults
this.totalResults = Object.keys(this.responseData).length
console.log(Object(this.responseData));
})
.catch((error)=>{
console.log(error)
})
}
},
computed: {
filteredObject(){
return this.responseData
},
test(){
var fullResults = Object(this.responseData);
var number = 0;
for (var key in fullResults) {
number++;
if(!number > 6){
this.filteredData[number] += fullResults[key]
}
}
console.log(this.filteredData)
},
// Set totalResults with matching string
resultString(){
if(this.totalResults == 1){
return this.totalResults + ' resultaat'
}else{
return this.totalResults + ' resultaten'
}
}
}
})
app.mount('#v_search');
Your search result set should really be an array (of result objects).
Something like:
[
{"id": 1, "text": "foo"},
{"id": 2, "text": "bar"},
{"id": 3, "text": "baz"},
...
]
Or, more elegant:
{
"searchterm": "input value"
"total_results": 31,
"limit": 10,
"page": 2,
"results": [
{"id": 1, "text": "foo"},
{"id": 2, "text": "bar"},
{"id": 3, "text": "baz"},
...
]
}
Then, the computed should be as simple as:
data() {
return {
results: []
}
},
computed: {
resultsToShow() {
return this.results.slice(0, 6)
}
},
methods:{
fetchResults() {
axios.post('includes/searchproducts_json.php', {
// Post data, add value of input to searchterm
searchterm: this.$refs.searchterm.value
})
.then((response) => {
if (response.status === 200 && response.data.length) {
this.results = response.data
}
})
.catch(console.error)
}
}
See a working demo: https://codesandbox.io/s/thirsty-germain-i6w4w?file=/src/App.vue
And because it's just a simple slice, you could even remove (the overhead of) the computed property and just write it into the template inline expression:
<ol>
<li v-for="(result, index) in results.slice(0, 6)" :key="index">
{{ result.text }}
</li>
</ol>
Object.keys() returns an array of the object keys, which could be the thing you are looking for if i understand correctly. Then you could create a computed property something like this:
test() {
return Object.keys(this.responseData).map((key) => this.responseData[key]).slice(0,6);
}
This transforms the object to an an array after which you can use a simple slice method to get the first 6 elements.

Get the closest match in a string

I have a json file with some domains which I try to match in a foreach object function.
JSON-File:
"calendar-google": {
"domainMatch": "calendar.google",
"icon": "assets/icons/google-calendar.png"
},
"inbox-google": {
"domainMatch": "inbox.google",
"icon": "assets/icons/google-gmail.png"
},
"github": {
"domainMatch": "github",
"icon": "assets/icons/github.png"
},
"google": {
"domainMatch": "google",
"icon": "assets/icons/google-google.png"
},
"trello": {
"domainMatch": "trello",
"icon": "assets/icons/trello.png"
},
"tweetdeck": {
"domainMatch": "tweetdeck.twitter",
"icon": "assets/icons/twitter.png"
},
"twitter": {
"domainMatch": "twitter",
"icon": "assets/icons/twitter.png"
},
"youtube": {
"domainMatch": "youtube",
"icon": "assets/icons/youtube.png"
}
Now I want to check if my url in my local storage does match with one of these "domainMatch" properties.
JavaScript:
$.getJSON("domainList.json", function (data) {
Object.getOwnPropertyNames(data).forEach(function(val, idx, array) {
var domainMatch = data[val].domainMatch
if(localStorage.getItem("favouriteSite")) {
var sites = JSON.parse(localStorage.getItem("favouriteSite"));
// Lets think firstlink is "calender.google.com"
var firstLink = sites.site1.link;
if(firstLink.includes(domainMatch)){
// 2 Results but I want only that
// result which is near!!
}
}
});
You see in the comment, that I not want the match "google" and "calender.google". I want only the nearest match from both (calender.google in this case).
How can I get the nearest match of a string?
When I did not write something detailed enough, then please write it but I think you should understand what I mean.
Greetings
Julian
Use Array.prototype.some() function to return the result immediately on the first match:
$.getJSON("domainList.json", function (data) {
var matched = Object.keys(data).some(function(k) {
var domainMatch = data[k].domainMatch;
if (localStorage.getItem("favouriteSite")) {
var sites = JSON.parse(localStorage.getItem("favouriteSite"));
// Lets think firstlink is "calender.google.com"
var firstLink = sites.site1.link;
return firstLink.includes(domainMatch);
}
};
});
Instead of forEach, use find to get the first match or null if nothing is matched like this:
$.getJSON("domainList.json", function(data) {
var sites = JSON.parse(localStorage.getItem("favouriteSite")); // this should be out here (so you won't fetch it evertime)
var firstLink = sites.site1.link;
var val = Object.keys(data).find(function(key) { // find will stop at the first found item (Object.keys) is better since it's just a plain object)
var domainMatch = data[key].domainMatch;
return firstLink.includes(domainMatch);
});
console.log(val); // val will be the first matched key ('github', 'google', ...) or null if nothing is matched
/***************** EDIT: **********************/
if(val) { // if we found something
var obj = data[val]; // get the object (because val is the key)
var icon = obj.icon; // now obj is an object from the array data (you can access its icon property like this)
}
});

Search for a related json data

How can i find data that is related to the already known data?
( I'm a newb. )
For example here is my json :
[
{ "id": "1", "log": "1","pass": "1111" },
{ "id": 2, "log": "2","pass": "2222" },
{ "id": 3, "log": "3","pass": "3333" }
]
Now i know that "log" is 1 and i want to find out the data "pass" that is related to it.
i've tried to do it so :
The POST request comes with log and pass data , i search the .json file for the same log value and if there is the same data then i search for related pass
fs.readFile("file.json", "utf8", function (err, data) {
var jsonFileArr = [];
jsonFileArr = JSON.parse(data); // Parse .json objekts
var log = loginData.log; // The 'log' data that comes with POST request
/* Search through .json file for the same data*/
var gibtLog = jsonFileArr.some(function (obj) {
return obj.log == log;
});
if (gotLog) { // If there is the same 'log'
var pass = loginData.pass; // The 'pass' data that comes with POST request
var gotPass = jsonFileArr.some(function (obj) {
// How to change this part ?
return obj.pass == pass;
});
}
else
console.log("error");
});
The problem is that when i use
var gotPass = jsonFileArr.some(function (obj) {
return obj.pass == pass;
});
it searches through the whole .json file and not through only one objekt.
Your main problem is that .some() returns a boolean, whether any of the elements match your predicate or not, but not the element itself.
You want .find() (which will find and return the first element matching the predicate):
const myItem = myArray.find(item => item.log === "1"); // the first matching item
console.log(myItem.pass); // "1111"
Note that it is possible for .find() to not find anything, in which case it returns undefined.
The .some() method returns a boolean that just tells you whether there is at least one item in the array that matches the criteria, it doesn't return the matching item(s). Try .filter() instead:
var jsonFileArr = JSON.parse(data);
var log = loginData.log;
var matchingItems = jsonFileArr.filter(function (obj) {
return obj.log == log;
});
if (matchingItems.length > 0) { // Was at least 1 found?
var pass = matchingItems[0].pass; // The 'pass' data that comes with the first match
} else
console.log("error"); // no matches
Using ES6 Array#find is probably the easiest, but you could also do (among other things)
const x = [{
"id": "1",
"log": "1",
"pass": "1111"
}, {
"id": 2,
"log": "2",
"pass": "2222"
}, {
"id": 3,
"log": "3",
"pass": "3333"
}];
let myItem;
for (let item of x) {
if (item.log === '1') {
myItem = item;
break;
}
}
console.log(myItem);

Advanced Array.prototype.filter with Javascript

I have an Javascript object like so...
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
I then have an array that indicates which results I'd like back. It can be any of the following: [] OR ["war"] ["farming"] OR ["war", "farming"].
If we have the [], I want to return no results. But if ["war", "farming"] I want to return both of the results above.
How do I accomplish this with Array.prototype.filter? I saw this post, but couldn't reason through it.
strategies.filter((strategy) =>
????
)
Thanks for your help.
You can just check the value with indexOf:
var categories = ['war', 'farming'];
var filtered = strategies.filter((obj) => {
return categories.indexOf(obj.strategy.category) > -1;
});
Your object, strategy was a wrapped object, so my first line was setting it to its inner strategy and then filter as needed.
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
var b = ["war", "farming"];
strategies.filter(function(strategy){
strategy = strategy.strategy;
for(var i in b){
if (b[i] == strategy["category"]) {
return true;
}
}
return false;
});
Tests the input array to see if it's empty as per your requirements:
function filterObj(arr) {
return !arr.length ? arr :
strategies.filter((el) => arr.indexOf(el.strategy.category) > -1);
}
filterObj(['war', 'farming'])
DEMO

Categories

Resources