Can't seem to delete element in object literal [duplicate] - javascript

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 6 years ago.
I have a JSON object literal from which I'm trying to delete an element (let's say apples). I've tried many things, but I just can't seem to get it to work.
var JSON = {
"fruits": [{
"name": "oranges",
"quantity": "3"
},{
"name": "apples",
"quantity": "2"
},{
"name": "bananas",
"quantity": "3"
}
]};
console.log(JSON);
delete JSON.fruits[1];
console.log(JSON);
Calling the above code results in the object being removed, but it looks like then inserts the key before the 3rd object. Have a look at this fiddle. I don't want that to happen.
That's what happens in the Fiddle. But then in my live script however, it looks like it replaces the deleted object with the word null which breaks my script.
I've also tried many variations of .splice() but that seems to be for arrays, rather than object literals.
Any ideas?

You could use Array#splice for the array inside of the object.
delete deletes the object, but you get an undefined element of the array.
var object = { fruits: [{ name: "oranges", quantity: "3" }, { name: "apples", quantity: "2" }, { name: "bananas", quantity: "3" }] };
object.fruits.splice(1, 1);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JSON.fruits.splice(1, 1); // to remove apples
Knowledge: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Related

Creating an array of objects inside an object that already exists

I can create nested objects in Javascript like this:
var filter = {
filterColumns: {
value: "",
valueText:""
}
};
but how can I turn filtercolumns into an array of objects? for example I would like to be able to do this:
filter.filterColumns[26].value = "value"
filter.filterColumns[26].valueText = "Bob"
filter.filterColumns[32].value = "value"
filter.filterColumns[32].valueText = "Ibb"
etc.
Thanks
EDIT: Apologies, I got this completely wrong. My original post confused javascript with C#. I have re-written it to reflect what I am trying to do.
Do you mean something like the following?
var filter = {
filterColumns: [
{
value: "1",
valueText: "Alice"
},{
value: "2",
valueText: "Bob"
},{
value: "3",
valueText: "Charlie"
}
]
};
Now filter.filterColumns[1].valueText would contain the string "Bob";
You can for example add to the list with the following code:
filter.filterColumns.push({value: "4", valueText: "Daniel"});

How to pull a property like "customer.gender" from an array of object with map [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 4 years ago.
I am using javascript map to loop through an array of object. Today i have to loop through an array of object which looks like,
averageReport = [
{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
What i tried to get only the "customer.gender",
averageReport
.map(x => console.log(x.customer.gender)
)
I get the error "Cannot read property 'gender' of undefined"
code on stackblitz
Try,
averageReport
.map(x => console.log(x["customer.gender"])
Since you named your key customer.gender you can't use dot-notation to get the value, you have to use bracket notation ([]).
Also mapping to console.log() doesn't make much sense (since console.log() returns undefined, you are creating a new array of undefined when using map() here), just use forEach():
averageReport = [{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
averageReport.forEach(x => console.log(x["customer.gender"]));
If you want to access the property using dot-notation, you have to make customer an object and gender a property of it, like so:
averageReport = [{
"result": 150.54909908933223,
"customer": {
"gender": "Female"
}
},
{
"result": 150.35230422844595,
"customer": {
"gender": "Male"
}
}
];
Use bracket notation for accessing the customer.gender property. Try the following :
var averageReport = [ { "result": 150.54909908933223, "customer.gender": "Female" }, { "result": 150.35230422844595, "customer.gender": "Male" } ];
var result = averageReport.map(x =>x["customer.gender"]);
console.log(result);

Editing an object in nested data structure

I have a data structure like this:
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
"countryName":"MADRAS",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
My requirement is, I need to add Job Details under MADRAS to Tamil Nadu and I need to sort the data based on one property -PostedDate.
So my result should be something like,
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
I tried to extract Madras data and add that to under Tamil Nadu. But nothing is working.
I know how to extract single or multiple value from JSON object. But I need to edit that JSON and sort it. That I am able to do it.
I got the solution.
When the countryName is "Tamil Nadu" and "MADRAS",I extracted all the data and saved it in a new array using below code.
function mergingBothStateDetails(jsonJobDetails){
for(var j=0;j<jsonJobDetails.length;j++)
{
newTmpRecord.push({"RequisitionId":jsonJobDetails[j].RequisitionId,
"PostedDate":jsonJobDetails[j].PostedDate,
"City":jsonJobDetails[j].City});
}
}
Here newTmpRecord is an Array and is like universal variable
For sorting I used below codes
function sortNewList(){
newTmpRecord.sort(function(a, b){ // sort object by retirement date
var dateA=new Date(a.PostedDate), dateB=new Date(b.PostedDate)
return dateB-dateA //sort by date descending
});
}
You can simply extract the object "Madras" from the array and add all of its Jobdetails to the object "Tamil Nadu" in a for loop. You can either look where to add them in the loop by checking the dates, or you can write a sort function, which is pretty easy in javascript and well explained here:
You might want to look up objects
And here the sorting is explained.

Keep the sort order

I have a object with that values :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
}
}
And when I would like to show it Chrome reorders it based on the Index :
It becomes :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
}
}
I wish to keep the order as it was when pushing! or reorder based on field "order"
Can someone please help with that?
JavaScript objects are by definition unordered.
If you need an ordered list, you should use an array (of objects) instead, e.g.:
var objs = [
{
"key": 1000,
"name":"Cars",
"order": 1,
"level": 2
}, ...
];
objs.sort(function(a, b) {
return a.order - b.order;
});
NB: for numeric properties use numeric types.
JavaScript objects do not guarantee a specific order for their attributes. So the structure you'd like to have simply doesn't exist in JavaScript.
So with the native structures you can get either:
Array: Guaranteed order, but only accessing elements sequentially or by a numeric (0..n-1) index
Object: Arbitrary order, but you can access elements sequentially (again, arbitrary order) or using its key (which can be any string)
If you need both you either need to add an array that maps the order to the object keys, e.g. [1000, 2010, 1030] or store the data in an array and create a mapping like this: {1000: 0, 2010: 1, 1030: 2}.

How to sort an array of objects in ascending order of number?

I have an array of objects like the following :
var array = {
"112" : {
"id": "3",
"name": "raj"
},
"334" : {
"id": "2",
"name": "john"
},
"222" : {
"id": "5",
"name": "kelvin"
}
}
Now i want to sort the array in ascending order of id and then restore it in array. I tried using sort() but could not do it. Please help how to do so that when i display the data from the array it comes sorted.
Assuming you meant your code to be an array of objects, ie:
var unsortedArray = [
{ id: 3, name: "raj" },
{ id: 2, name: "john" },
{ id: 5, name: "kelvin" }
];
Then you would be able to sort by id by passing a function to Array.sort() that compares id's:
var sortedArray = unsortedArray.sort(function(a, b) {
return a.id - b.id
});
As others have pointed out, what you have is an object containing objects, not an array.
var array = {
"112" : {
"id": "3",
"name": "raj"
},
"334" : {
"id": "2",
"name": "john"
},
"222" : {
"id": "5",
"name": "kelvin"
}
}
var sortedObject = Array.prototype.sort.apply(array);
result:
{
"112": {
"id": "3",
"name": "raj"
},
"222": {
"id": "5",
"name": "kelvin"
},
"334": {
"id": "2",
"name": "john"
}
}
That isn't an array, it is an object (or would it if it wasn't for the syntax errors (= should be :)). It doesn't have an order.
You could use an array instead (making the current property names a value of a key on the subobjects).
Alternatively, you could use a for loop to build an array of the key names, then sort that and use it as a basis for accessing the object in order.
JavaScript objects are unordered by definition. The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you need things to be ordered, use an array and the Array.prototype.sort method.
That is an object but you can sort an array ilke this:
Working Demo: http://jsfiddle.net/BF8LV/2/
Hope this help,
code
function sortAscending(data_A, data_B)
{
return (data_A - data_B);
}
var array =[ 9, 10, 21, 46, 19, 11]
array.sort(sortAscending)
alert(array);​
Not many people knows that Array.sort can be used on other kinds of objects, but they must have a length property:
array.length = 334;
Array.prototype.sort.call(array, function(a, b) {return a.id - b.id;});
Unfortunately, this doesn't work well if your "array" is full of "holes" like yours.

Categories

Resources