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);
}
Related
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
})
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);
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
.
So lets say I have some JSON:
{
"users": [{
"name": "bob",
"age": 16,
"likes": ["cats", "kayaking", "knitting"]
}, {
"name": "kyle",
"age": 19,
"likes": ["dogs", "soccer", "baseball"]
}, {
"name": "mike",
"age": 18,
"likes": ["cats", "cars", "kayaking"]
}]
}
and I want to go through that and return all user objects with the likes that include "cats" and "kayaking". I'm using lodash and there doesn't seem to be a lodash method to do that. I only see _.findKey and _.includes. Is there a method or group of methods that I can use that'll do this or am I better off just using vanilla javascript?
You are looking for _.filter():
var output = _.filter(input.users, function(item) {
return _.includes(item.likes, 'cats')
&& _.includes(item.likes, 'kayaking');
});
It filters the array using the filter function you specify. If this filter function returns true for a given item of the array, this item will be included in the resulting array.
If you want to use Vanilla JS:
You can use indexOf along with a comparator array for comparison.
Using this comparator array, you can filter the results to return only the objects that match the criteria.
Additionally use a reduce method to return true or false depending on whether or not one of the strings in the array matches your comparator array.
var comparator = ['dogs', 'baseball'];
var dogsAndBaseball = obj.users.filter(function(obj) {
return obj.reduce(function(acc, cur) {
return acc || comparator.indexOf(cur) > -1;
}, false);
});
This will return
[{
"name": "kyle",
"age": 19,
"likes": ["dogs", "soccer", "baseball"]
}]
I have the following problem:
I have a JSON table with the data I need (found this on the internet since it is nearly what I need)
var testext ={"key1":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
},
{
"firstName":"John",
"lastName":"Jones",
"joined":2010
}
]}
document.getElementById("demo").innerHTML=testext.key1[0].firstName;
This works fine but as you can see I still need an index [0] to get to the dataset I need.
I need to to this without this index...
like this here:
var testext = {
"key1": ["string1/1", "string1/2" ],
"key2": ["string2/1", "strin2/2"]
};
document.getElementById("demo").innerHTML = testext['key1'][0];
just combined so my variable would be something like :
document.getElementById("demo").innerHTML = testext['key1'].['firstname'];
Anyone an idea on how I can do this?
Thanks in advance.
You are almost correct. Restructure your array into an associative array of associative arrays. You can call them by array_name['first_index']['second_index'].
var testext = {
"key1": {
"firstName": "Ray",
"lastName": "Villalobos",
"joined": 2012
},
"key2": {
"firstName": "John",
"lastName": "Jones",
"joined": 2010
}
};
document.getElementById("demo").innerHTML = testext['key1']['firstName'];
<div id="demo">Default</div>