Deleting element and changing element property in an Array of objects - javascript

So there is an array of object called employees that has employee's credentials.
I am supposed to delete the object if the employee's name is Theo, and if the employee's name is Lorie I should change the department's property to 'HR'
I've tried using a for loop to go through the objects in the array and change their properties. but it would not return the iterated array.
maybe I need to use the .reduce() method
Here is the code I've tried

It should be working!
Your array of objects.
var employees = [
{
"firstName": 'Von',
"lastName": 'budibent',
"email": "email#mail.com",
"departement": "Sales"
},
{
"firstName": 'Theo',
"lastName": 'Trill',
"email": "email#mail.com",
"departement": "Services"
},
{
"firstName": 'Lorie',
"lastName": 'Trill',
"email": "email#mail.com",
"departement": "Research and Development"
}
];
Then you need to filter by firstName and then mapping the data.
var adjustedEmployees = employees
.filter(employee => employee.firstName !== 'Theo')
.map((employee) => {
if (employee.firstName === 'Lorie') employee.departement = 'HR';
return employee;
});

//I needed to use a function with no parameters, I figured out how to do it.
Solved question

//Remove employe with firstname 'Theo'
var result = employees.filter(employee => employee.firstName !== 'Theo');
//Change department of Lorie to 'HR'
result.forEach(el => {
el.departement = el.firstName === 'Lorie' ? 'HR' : el.departement
})

Related

findIndex() returns as -1 and not correct index number

Struggling with this one. It was working before and not sure, why it is not now...
I have a ToDo app, containing a form, with two inputs - one for name. And one for url.
I should be able to edit any input value. And then save/update the updated array object, in local storage.
If I click on my edit button, without changing an input value, the correct index number is returned, (0 or 1).
But if I change an input value. And THEN click the edit value, -1 is returned.
And therefore, the rest of my function does not work, as my JS is not finding the correct index to update, the object with.
Here's a snippet of the code. What am I doing wrong?
bookmarksArray: [
{
"name": "jane",
"url": "http://www.jane.co.uk/"
},
{
"name": "mark",
"url": "http://www.google.com"
}
]
// UPDATE/EDIT EXISTING BOOKMARK
list.addEventListener('click', event => {
if (event.target.classList.contains('js-edit-url')) {
const editName = event.target.parentElement.name.value;
const editURL = event.target.parentElement.url.value;
let constUpdatedOBj = {name: editName, url: editURL};
const objIndex = bookMarksArray.findIndex(obj => obj.name === editName);
console.log('editName', editName);
console.log('editURL', editURL);
console.log('objIndex', objIndex);
bookMarksArray[objIndex] = constUpdatedOBj;
window.localStorage.setItem("bookMarksArray", JSON.stringify(bookMarksArray));
}
});
This is working as I would expect it to, if you start out with your array like so:
bookmarksArray: [
{
"name": "jane",
"url": "http://www.jane.co.uk/"
},
{
"name": "mark",
"url": "http://www.google.com"
}
];
And then the name mark is edited in the input to tony, this is essentially what you're getting:
const objIndex = bookMarksArray.findIndex(obj => obj.name === 'tony');
"tony" doesn't exist in the bookmarksArray so findIndex is going to return a -1.
What you need is an id on those bookmarks:
bookmarksArray: [
{
"id": 1,
"name": "jane",
"url": "http://www.jane.co.uk/"
},
{
"id": 2,
"name": "mark",
"url": "http://www.google.com"
}
];
And then have your findIndex look for the correct record based on the id:
const bookmarkId = event.target.parentElement.id.value;
const objIndex = bookMarksArray.findIndex(obj => obj.id === bookmarkId);

Adding multiple pieces of data to a single row in javascript

I am currently working on a website that imports JSON data and populates a table within HTML. In this instance the JSON file has already been parsed and exists as an JavaScript object.
I am having trouble iterating through the arrays within the object to try and add data with different key values to a single table row.
what I want to achieve is to have the names of each employee who works in a particular department to be present in a single row.
I started by creating an empty array outside my for loops.
I have iterated through the object using three separate for loops and appended the names of the employees to this empty array. After my loops i have let my now full array that contains the names equal to an empty array.
What i have been working on can be seen here https://jsfiddle.net/kn0y9g5d/
<div id="id01"></div>
<script>
const table =
{ "Employees":
[ { "Started" : "2016"
, "Department": "Engineering"
, "Employee":
[ { "id": "a101", "firstname": "Alan", "surname": "Arkin" }
, { "id": "a102", "firstname": "Geoff", "surname": "keegan" }
]
}
, { "Started" : "2016"
, "Department": "R&D"
, "Employee":
[ { "id": "a103", "firstname": "Michele", "surname": "Jones" }
, { "id": "a104", "firstname": "Peter", "surname": "Smith" }
]
}
]
}
var DepName =[];
var employeeNames =[];
let MyTable = document
.querySelector('#id01')
.appendChild(document.createElement('table'))
for (let StartDep of table.Employees)
{
for (let Employee of StartDep.Employee )
{
for (let Employee1 of StartDep.Employee ){
var name = Employee1.firstname + " " + Employee1.surname
employeeNames.push(name)
let nRow = MyTable.insertRow(-1)
, rCell = 0
nRow.insertCell(rCell++).textContent = StartDep.Started
nRow.insertCell(rCell++).textContent = StartDep.Department
nRow.insertCell(rCell++).textContent = employeeNames
}employeeNames=[];
}
}
let Rowhead = MyTable.createTHead().insertRow(-1)
'Started,Department,Name(s)'.split(',')
.forEach((T,i)=>Rowhead.insertCell(i).textContent=T)
</script>
what I expect to get using this code will be similar to this https://i.stack.imgur.com/Vgvlo.png
console.log(table);
const abc = [];
for(var j=0;j<2;j++)
{
const gh = [];
for(var i =0;i<2;i++)
{
let name = table.Employees[j].Employee[i].firstname+" "+table.Employees[j].Employee[i].surname
gh.push(name);
}
var totalName = gh.join();
abc.push(totalName);
}
console.log(table.Employees[0].Employee[0].firstname);
console.log(abc);
if you do this before appending this to table you should be able to get the result easily
i did it on my own so i cant give you any reference to look at.
hope this helps

Postman get value from JSON where equals a value in array using javascript

Currently using the latest version of Postman: 6.7.4 (Latest)
I'm trying to get a value out of a JSON response body and store it in an environment variable BUT the value 'username' should be equal to my preferred username.
Normally I would extract a value like this:
var jsonData = pm.response.json();
pm.environment.set("useridToken", jsonData.Customers[0].userid);
This would give me the first item in the list but I do not wish to obtain the first nor the second item from the list. I wish to obtain the userid where username EQUAL "Billy" for example.
Output of the body response:
{
"Customers": [
{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
}
Any tips?
I remember in SoapUI it was like this:
$.channels[?(#.is_archived=='false')].id[0]
I guess it's not possible to do this in JS in Postman?
You can use: Array.prototype.find():
const data = {
"Customers": [{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME"
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
}
const user = data.Customers.find(u => u.username === 'Billy')
const userid = user ? user.userid : 'not found'
console.log(user)
console.log(userid)
find() as another answer points out is the best solution here, but if the username is not unique and you want an array of users where username is 'Billy' then use filter()
const jsonData = {
"Customers": [{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME"
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
}
console.log(jsonData.Customers.filter(c => c.username === 'Billy'))
In Postnam test script, you can use some Javascript features. In your case, too many way to do.
I will show you how to solve your case with Array.find function:
var jsonData = pm.response.json();
var user = jsonData.Customers.find(function(user) {
return user.username === 'Billy';
// OR you could config username in postman env
// return user.username === pm.variables.get("username_to_find");
});
pm.environment.set("useridToken", user.userid);
Your userid can also be obtained using filter as follows -
const data = {
"Customers": [{
"id": 24,
"userid": 73063,
"username": "BOB",
"firstname": "BOB",
"lastname": "LASTNAME"
},
{
"id": 25,
"userid": 73139,
"username": "Billy",
"firstname": "Billy",
"lastname": "lasty"
}
]
};
const username = 'Billy';
const user = data.Customers.filter(obj => obj.username.toLowerCase() === username.toLowerCase())[0];
const userid = user ? user['userid'] : null;
console.log(userid);
Note: .toLowerCase() is optional here, you may use it depending on your condition.
Then you could simply set it as -
pm.environment.set("useridToken", userid);
This answer is inspired by the
other answer that outputs an array.
1
It is not clearly stated by the original poster whether the desired output
should be a single userid (presumably the first occurence?) - or
an array containing all userid:s matching "Billy".
This answer shows a solution to the latter case by using
Lodash.
const jsonData = {
Customers: [{
userid: 73063,
username: 'BOB'
}, {
userid: 73138,
username: 'Billy'
}, {
userid: 74139,
username: 'Billy'
}]
};
const userIds = [];
_.forEach(_.filter(jsonData.Customers, c => c.username === 'Billy'),
item => { userIds.push(item.userid); });
console.log(userIds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>
1 That answer is quite helpful as it hints how to filter out
the relevant objects of the Customers array. However, the original poster
wants (an array of) the userid(s) which is a number, and not an an array
of objects that contains the userid:s. This is how my answer here is
different.
Try this
const userid = data.Customers.find(u => u.username === 'Billy') || 'not found';
This answer shows a solution using the JavaScript library
Lodash.
This is not meant as a recommendation, but merely to prove that it is
possible to use Lodash.
It is inspired by
the other lodash answer.1
const jsonData = {
Customers: [{
id: 24,
userid: 73063,
username: 'BOB',
firstname: 'BOB',
lastname: 'LASTNAME'
}, {
id: 25,
userid: 73139,
username: 'Billy',
firstname: 'Billy',
lastname: 'lasty'
}]
};
const userId_Lodash = (name) => {
let userId;
_.forEach(jsonData.Customers, (item) => {
if (item.username === name) { userId = item.userid; }
});
return userId;
};
console.log('Lodash loop, userid of "Billy": ' + userId_Lodash('Billy'));
console.log('Lodash loop, userid of "Dave": ' + userId_Lodash('Dave'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>
For the question at hand, I don't see any particular reason to use the Lodash
library.
But in other examples it could make all the more sense.
1 The posted question does not state whether the desired outcome is
the first userid matching Billy, or all such userid:s.
This answer gives the first hit.
Repeating
the currently highest voted answer,
slightly modified.
Also adding a solution inspired by
the other Lodash answer.1
const jsonData = {
Customers: [{
id: 24,
userid: 73063,
username: 'BOB',
firstname: 'BOB',
lastname: 'LASTNAME'
}, {
id: 25,
userid: 73139,
username: 'Billy',
firstname: 'Billy',
lastname: 'lasty'
}]};
for (const i in jsonData.Customers) {
console.log('userid of customer['+i+']: '+jsonData.Customers[i].userid);
}
const userId_UsingFind = (name) => {
const user = jsonData.Customers.find(item => item.username === name);
return user ? user.userid : user;
};
console.log('Using .find(), userid of "Billy": '+userId_UsingFind('Billy'));
console.log('Using .find(), userid of "Joe": '+userId_UsingFind('Joe'));
const userId_Native = (name) => {
for (const i in jsonData.Customers) {
if (jsonData.Customers[i].username === name) {
return jsonData.Customers[i].userid;
}
}
};
console.log('Native loop, userid of "Billy": '+userId_Native('Billy'));
console.log('Native loop, userid of "Joe": '+userId_Native('Joe'));
As the code shows, the solution using .find() is both short and elegant.
1 Assuming the desired outcome is the userid of the first
Billy. To retrieve an array of userid:s for all occurrences
ofBilly, see the answer that returns an array of userid:s
.

Mustache.js - know if a list only has a single item

currently i'm looping through using mustache when i came across the display of authors..
{{#authors}}{{.}}, {{/authors}} //loop through each author names in authors array
the issue is the comma at the end. i prefer the data (JSON from server) untouched. is there a way in mustache to know if you are in the last iteration (and not append a comma) or know if you are in the first iteration (and not prepend a comma)
Not tested!
Overview: add a prefix of ", " for all but the first name.
Template:
{{#beatles}}
{{name}}
{{/beatles}}
Initialize:
window.app.first_flag = true; // initialize
// assumes that the app has created the window.app object/hash to
// hold the app's data
View:
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
var n = this.firstName + " " + this.lastName,
prefix = ", ";
if (window.app.first_flag) {
window.app.first_flag = false;
prefix = "";
}
return prefix + n;
}
}

Remove JSON element

I want to remove JSON element or one whole row from JSON.
I have following JSON string:
{
"result":[
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
}
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
Do NOT have trailing commas in your OBJECT (JSON is a string notation)
UPDATE: you need to use array.splice and not delete if you want to remove items from the array in the object. Alternatively filter the array for undefined after removing
var data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.
data = {
"result": [{
"FirstName": "Test1",
"LastName": "User"
}, {
"FirstName": "user",
"LastName": "user"
}]
}
console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.
You can try to delete the JSON as follows:
var bleh = {first: '1', second: '2', third:'3'}
alert(bleh.first);
delete bleh.first;
alert(bleh.first);
Alternatively, you can also pass in the index to delete an attribute:
delete bleh[1];
However, to understand some of the repercussions of using deletes, have a look here
For those of you who came here looking for how to remove an object from an array based on object value:
let users = [{name: "Ben"},{name: "Tim"},{name: "Harry"}];
let usersWithoutTim = users.filter(user => user.name !== "Tim");
// The old fashioned way:
for (let [i, user] of users.entries()) {
if (user.name === "Tim") {
users.splice(i, 1); // Tim is now removed from "users"
}
}
Note: These functions will remove all users named Tim from the array.
I recommend splice method to remove an object from JSON objects array.
jQuery(json).each(function (index){
if(json[index].FirstName == "Test1"){
json.splice(index,1); // This will remove the object that first name equals to Test1
return false; // This will stop the execution of jQuery each loop.
}
});
I use this because when I use delete method, I get null object after I do JSON.stringify(json)
All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:
var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];
This way the garbage collector for node.js will know that json['somekey'] is no longer required, and will delete it.
Fix the errors in the JSON: http://jsonlint.com/
Parse the JSON (since you have tagged the question with JavaScript, use json2.js)
Delete the property from the object you created
Stringify the object back to JSON.
As described by #mplungjan, I though it was right. Then right away I click the up rate button. But by following it, I finally got an error.
<script>
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"h.prajapati#zzz.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result)
delete data.result[3]
alert(data.result)
</script>
Delete is just remove the data, but the 'place' is still there as undefined.
I did this and it works like a charm :
data.result.splice(2,1);
meaning : delete 1 item at position 3 ( because array is counted form 0, then item at no 3 is counted as no 2 )
Try this following
var myJSONObject ={"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
console.log(myJSONObject);
console.log(myJSONObject.ircEvent);
delete myJSONObject.ircEvent
delete myJSONObject.regex
console.log(myJSONObject);
if we want to remove one attribute say "firstName" from the array
we can use map function along with delete as mentioned above
var result= [
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
result.map( el=>{
delete el["FirstName"]
})
console.log("OUT",result)
Could you possibly use filter? Say you wanted to remove all instances of Ropbert
let result = [
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
result = result.filter(val => val.FirstName !== "Ropbert")
(result now contains)
[
{
"FirstName": "Test1",
"LastName": "User",
},
{
"FirstName": "user",
"LastName": "user",
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
}
]
You can add further values to narrow down the items you remove, for example if you want to remove on first and last name then you could do this:
result = result.filter(val => !(val.FirstName === "Ropbert" && val.LastName === "Jones"))
Although as noted, if you have 4 'Ropbert Jones' in your array, all 4 instances would be removed.
try this
json = $.grep(newcurrPayment.paymentTypeInsert, function (el, idx) { return el.FirstName == "Test1" }, true)
A descent Solution is here
My JSON array is
const [myData, setData] = useState([{username:'faisalamin', share:20}, {username:'john', share:80}])
I want to delete john on a button click in renderItem or in .map
const _deleteItem = (item) => {
const newData = myData.filter(value => { return value.username !== item.username });
setData(newData);
}

Categories