Delete property of an array object using javascript - javascript

I have an array object in the below format and need to delete a property of an array.
Code:
var partDetailArray={[PartId:100,PartRowID:'row-1']
,[PartId:100,PartRowID:'row-1']};
delete partDetailsArray.PartRowID;
I need to remove the PartRowID property from the array, but the delete statement isn't working.

If you look in the console, you'll see that you're getting syntax errors with that code for the reasons I put in my comment on the question.
I'm going to guess you meant to have an array containing objects, like this:
var partDetailArray = [
{PartId:100,PartRowID:'row-1'},
{PartId:100,PartRowID:'row-1'}
];
In that case, the array doesn't have a PartRowID property, but each of the objects in it does. So we need to index into the array to access the object, and delete the property from it:
delete partDetailsArray[0].PartRowID;
// Indexing into it ---^^^
That would delete that property from the first one. If you want to delete all of them, you'll need a loop:
var index;
for (index = 0; index < partDetailArray.length; ++index) {
delete partDetailsArray[index].PartRowID;
}

Related

Issue when splicing array of objects

I have a vue application that gets a set of objects from an external REST API.
In a component, I sort and filter the object into an array of objects based on a field called rank, like this:
let myResults = _.orderBy(this.search_result, 'rank', 'desc').filter(service => (service.rank >= 5) ? service: "");
I then need to move a single element/object to the end of the list before rendering it, however, when I tried to do this:
let index = myResults.findIndex(e => e.name === 'Target Element');
myResults.push(myResults.splice(index,1));
It didn't work; It pushed an empty element back to the list. Eventually, I got it working by doing the following:
myResults.push(myResults.splice(index,1)[0]);
I noticed the splice was creating an array that looked like [object, object] with all the target object in the zero index object.
I don't really understand why this happened. Have I done something to the original object somewhere or is this a vue thing?
JavaScript Array.prototype.splice() returns an Array.
Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
Since an Array is returned, you're .push()-ing and Array into an existent array. As you noticed correctly, you need to extract that one Object using removedItems[0], making
myResults.push(myResults.splice(index,1)[0]);
or equally
// Remove from array 1 item
const removedItems = myResults.splice(index, 1); // Array of removed items
// Get the first Object from array
const item = removedItems[0]; // Object
// Append one Object
myResults.push(item);
the correct approach.

What is the correct way to access nested objects in JSON?

If I understand correctly, list in this code is an array that consists of objects. I want to access temp in the main object and thought main.temp would do the trick, but I get an error message stating it’s undefined. Alternatively I’ve tried list[1].main.temp. What is the correct way to access nested arrays like this?
What is the correct way to access nested arrays like this?
First of all these aren't nested arrays, but array of objects instead and in an array we access the items by index, and in objects we access them(entries) by keys.
So in your case list[0] is an object where list[0].dt is an entry and list[0].main is another entry of the object, so dt isn't at index 0 like you mentioned in your comment.
And to access all your array main.temp properties you need to loop throught the array elements using one of the Array built-in methods or just a for loop, because using static indexes in list[1].main.temp will just get the temp property of the firts element in the array and may throw an exception if this index is higner than the array.length.
This is how should be your code:
for(var i=0; i<list.length; i++){
console.log(list[i].main.temp);
}

put content of all elements of class into array..why do i get these error messages

I'm trying to load text of all divs that have a particular class into an array, but this
var temp = $('.theClass').text();
temp = temp.toArray();
console.log(temp);
keeps giving me the error
Uncaught TypeError: Object has no method 'toArray'
And
var tempArr = [];
var temp = $('.theClass').text();
for (var t in temp){
tempArr.push(t);
}
console.log(tempArr);
results in an array filled with many, many objects within objects just filled with integers.
An explanation of how to do this properly can be found here, but I wonder if someone could provide me with an explanation for why I get these errors. Thanks!
You can use map to iterate over each element of the matched set and return some data (in this case, the text). You can then use get to convert the resulting jQuery object into an actual array:
var arr = $('.theClass').map(function () {
return $(this).text();
}).get();
Your first attempt fails because the text method returns a string, and strings don't have a toArray method (hence your "Object has no method" error).
Your second attempt fails because you're iterating over the string with the for...in loop. This loop iterates over the characters of the string. Each iteration t is assigned the index of the character, so you end up with an array, with one element for each character in the string. You should never really be using a for...in loop for iterating over anything other than object properties, and even then, you should always include a hasOwnProperty check.

jQuery delete array index

I'm having trouble deleting/removing an item from an Array in jQuery. I've run the results in console.log() and it shows up as an Object. I've created a function which returns a json string and then I parses it, an example below:
var ret = jQuery.parseJSON($.return_json(data));
It works nicely, however, I am running an $.each loop which removes items from that array/object.
var old = $("element").find("li[rel=item]");
$.each(old, function(index, value) {
ret.splice($(value).attr("id"), 1);
});
Above, I am searching for elements with attribute rel = item. The same element contains an id which is related to the index of the function which returns the json parsed variable.
I ran Developers Tools in Google Chrome to see the error and it prints:
Uncaught TypeError: Object #<Object> has no method 'splice'
Any words of guidance will be much appreciated. Thanks.
It seems like ret is not actually an array (and likely an object (ex: {someName: "someVal"}) instead).
I'm also making an assumption that you mean for $(value).attr("id") to be a string identifier like someName in the object example above. If that is the case and you are working with an object and you do have the appropriate property identifier, then luckily there is an easier solve than splice.
Try:
$("element").find("li[rel=item]").each(function() {
delete ret[$(this).attr("id")];
});
splice is only a method of arrays, not objects. ret in this case, is an object, not an array.
If you are trying to remove specific elements from an object, you can do this:
$("element").find("li[rel=item]").each(function(i,v){
delete ret[v.id];
});
ps. You can use .each instead of $.each.
If you really want to make the object into an array, you can simply loop through it and push the elements into an array.
var obj = {"1":"item 1", "2": "item 2", "3": "Item 3"};
var arr = [];
for(i in obj){
if(obj.hasOwnProperty(i)){
arr.push(obj[i]);
}
}
ret is the JSON object containing the array, and you can't splice it. You need to reference whatever you called the array within the object and splice that.
(Would help if you posted the code where you define the array).

push associative array error?

I have to push elements in an associative array from another array after some processing and I'm doing something this:
for(var i in this.aNames) {
var a = this.aNames[i];
// some processing on a
aList[i] = a;
aList.push(i);
}
But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.
I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.
There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList? Is it an array? If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
arr = []; // arr is an array
arr.push(obj["name"]); // arr now contains a single element, 'dreas'
In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop. If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.
Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
anArray = [1,2,3];
anObject["name"] <= member (results in "dreas")
anArray[1] <= element (results in 2)

Categories