string replace array map [duplicate] - javascript

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 6 years ago.
I have a hundreds of user in the list, below is just an example list :
var userList = [
{
"FullName": "test1",
"UserName": "test1",
"Email": "test1#test.com"
},
{
"FullName": "test2",
"UserName": "test2",
"Email": "test2#test.com"
}
];
var userStr = "test1 is doing a test2";
userList.map((user) => {
userStr.replace(RegExp(user.FullName,"gi"), user.Email)
})
console.log(userStr);
The test string return is still the same and is not replace with email. Is the code I do optimize?

You need to update the variable with the returned value.
var userList = [{
"FullName": "test1",
"UserName": "test1",
"Email": "test1#test.com"
}, {
"FullName": "test2",
"UserName": "test2",
"Email": "test2#test.com"
}];
var userStr = "test1 is doing a test2";
userList.forEach((user) => userStr = userStr.replace(RegExp(user.FullName, "gi"), user.Email))
console.log(userStr);

Related

How to access role property of userdata which is on mock json server

This is my Json data
{
"LoginData": [
{
"name": "Nick",
"password": "123",
"role": "employee"
},
{
"name": "Ratan",
"password": "123",
"role": "manager"
},
{
"name": "Rahul",
"password": "123",
"role": "admin"
}
]
}
By using filer method with name i get specific data and stored it in variable userData
[{name: 'Rahul', password: '123', role: 'admin'}]
But i cannot access its role using userData.role it gives undefined
what change should i do so that it gives me userData.role === "admin"
When you use filter function, you get array in output. You should consider using find method.
Also, I would recommend you to learn about array methods on MDN Docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
According to the docs, Array#filter returns:
A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.
Therefore, you need to access the first element in the returned array first:
const data = {
"LoginData": [
{ "name": "Nick", "password": "123", "role": "employee" },
{ "name": "Ratan", "password": "123", "role": "manager" },
{ "name": "Rahul", "password": "123", "role": "admin" }
]
}
const userData = data.LoginData.filter(({ name }) => name === 'Rahul');
const role = userData[0]?.role;
console.log(role);
If there's always max one item matching, Array#find would be better here:
const data = {
"LoginData": [
{ "name": "Nick", "password": "123", "role": "employee" },
{ "name": "Ratan", "password": "123", "role": "manager" },
{ "name": "Rahul", "password": "123", "role": "admin" }
]
}
const userData = data.LoginData.find(({ name }) => name === 'Rahul');
const role = userData?.role;
console.log(role);

Get an adjacent value in JSON array if value is found [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
If I have this type of object returned in javascript (as a result of $get)
[
{
"id": "1",
"username": "john"
},
{
"id": "2",
"username": "bill"
}
]
How would I search for the username "john" and if it exists return his ID
Thanks
i.e.
$.get( baseURL + "users/")
.done(function( data ) {
var usernames = data.results;
});
Use find():
var array =[
{
"id": "1",
"username": "john"
},
{
"id": "2",
"username": "bill"
}
];
var id = array.find(k=>k.username=='john')?.id;
console.log(id);

JSON Array - select from array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've got example array:
{
"orders": [
{
"order_id": 1,
"email": "alex#alex.com",
"city": "London"
},
{
"order_id": 2,
"email": "tom#tom.com",
"city": "Miami"
}
]
}
and variable var email = "tom#tom.com".
I have to select order_id and city from array where email = "tom#tom.com"
Have you got any ideas how to do it?
By using .filter() and .map():
const data = { "orders": [{ "order_id": 1, "email": "alex#alex.com", "city": "London" }, { "order_id": 2, "email": "tom#tom.com", "city": "Miami" }] };
const result = data.orders.filter(({email}) => email === 'tom#tom.com')
.map(({order_id, city}) => ({ order_id, city }));
console.log(result);
Try this below:
let json = {
"orders": [
{
"order_id": 1,
"email": "alex#alex.com",
"city": "London"
},
{
"order_id": 2,
"email": "tom#tom.com",
"city": "Miami"
}
]
}
var email = "tom#tom.com"
json['orders'].map(function(item){
if (item.email == email){
console.log(item.order_id);
console.log(item.city);
}
});

Find where item is in JSON array by given value

My JSON is:
"people": [
{
"id": "1",
"firstName": "John",
"lastName": "Smith"
},
{
"id": "2",
"firstName": "Ashton",
"lastName": "Negus"
},
{
"id": "3",
"firstName": "Roy",
"lastName": "Murrey"
}
]
I want to find where an item is by given value.
E.g. if I ask for id 1, I will get 0 because it's the first item in the array. If I ask for id 2, I will get 1 because that's the second item in the array, and so on.
Any help appreciated!
Use findIndex
var idToSearch = "1";
var index = people.findIndex( s => s.id == idToSearch );

Unable to delete an array element using splice in jQuery $.each loop

Hi I have an object which has only one property as "contacts" and its value is an array which contains 4 objects and each object has properties like email, firstname etc...
I want to remove a particular object from that array by matching its email property with an given email.
I am trying to iterate through that array using $.each loop in jQuery and trying to match email in each iteration and when matched I am trying to delete that object using splice but it is not working.
Below is a sample code similar to what I am implementing:
//main object with all the data
var data = {
"contacts": [
{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElement(myId){
//iterating the myArray to check the email with the given email
$.each(myArray, function(key, val){
var email = val.email;
//if the email is matched the particular object on the current index in the array is deleted using splice
if(myId === email){
myArray.splice(key,1);
return;
}
});
}
//calling the function and passing the email to delete the object
deleteElement(email);
//printing the modified array
console.log(myArray);
This method is not working so can you please let me know how can I make this work.
Note: I don't want to modify anything with the data object or myArray but I want to find solution with the current situation
Big Thanks
I would advise against the use of jQuery (because you don't need it) and against any for/while loop, and just KISS it :
function deleteElementWithEmail(data, email) {
return data.filter(function (current) {
return current.email !== email
})
}
With all your code:
//main object with all the data
var data = {
"contacts": [
{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElementWithEmail(data, email) {
return data.filter(function (current) {
return current.email !== email
})
}
//calling the function and passing the email to delete the object
myArray = deleteElementWithEmail(myArray, email);
//printing the modified array
console.log(myArray);
Use a do..while loop or while loop to remove elements from an array within a loop
let i = 0;
let len = data.contacts.length;
do {
var email = data.contact[i].email;
if (myId === email) {
data.contacts.splice(i, 1);
break;
}
++i;
} while (i < len);
You can use array.filter function to get desired result.
//main object with all the data
var data = {
"contacts": [{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//console.log(myArray);
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElement(myId) {
myArray = myArray.filter(function(el) {
return el.email != myId;
});
}
//calling the function and passing the email to delete the object
deleteElement(email);
//printing the modified array
console.log(myArray);

Categories