Removing a nested object using underscore.js _.omit - javascript

I have a nested object e.g:
data.object = [Object],[Object],[Object],[Object]
I want to completely remove the 3rd Object, so data.object[2] should no longer exist and I should see:
data.object = [Object],[Object],[Object]
Using delete retains the 3rd object but as undefined:
data.object = [Object],[Object],undefined,[Object]
I understand that _.omit can be used in a similar way but my attempts do not work:
_.omit(data.object,data.object[2])

No need to use underscore or any other third party library
data.object.splice(2, 1);
There is a standard JS function for that. It mutates the given array in-place, and removes the 1 element at the index 2.
References:
Array.prototype.splice()

Related

difference between javascript array and jquery set

I'm relatively new to javascript and very new to jquery.
I have noticed that the jquery set returned by jQuery() selector shares a lot of similarities with javascript array e.g. elements in the jquery set can be accessed by the square bracket [] syntax
So I was wondering, is there any foundamental difference between jquery set and javascript array? Or they can be thought of as two ways of representing the same thing?
From their own docs (found here):
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
So a jquery object is sort of array like, but it's not an array. Basically, an array will have methods the jquery object lacks, and the jquery object has methods that arrays lack. I would generally try not to treat the jquery objects as arrays, and instead try to use a jquery method whenever tempted to use an array method (ie, use .each instead of the array method .forEach).
EDIT:
After reading more about the jquery objects, they do share a lot of methods with arrays, such as .find. Moreover, it also provides a .toArray method which can be used to convert the jquery object into an actual javascript array.
As the person who was responsible for this jQuery feature, I thought I would share some historical notes.
If you study the jQuery API, you may notice something odd: the object returned by $()/jQuery() is not only an "array-like" object with a .length property and [i] access to its elements, but it also has a couple of fairly redundant methods: .get(i) and .size().
.get(i) is very similar to an array's [i]: it returns one of the elements of the jQuery array/object. And .size() is the same as .length.
In fact, if you look at the implementation of .size() you will see that it simply returns the .length property:
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
There is a little more to .get(). If you don't pass an argument, it is the same as .toArray(), and if you do pass an argument it allows both positive and negative indexes. Negative indexes count backwards from the end of the array similar to Python or Ruby.
But for the simple case of a non-negative index, .get(i) boils down to:
// Get the Nth element in the matched element set
get: function( num ) {
return this[ num ];
},
Why all this redundancy? .size() and .get(i) just do the same thing as the usual .length or [i], so why have both?
In the very first jQuery release in January 2006 (long before 1.0), the object returned by $() was not an "array-like" object. It was just a JavaScript object with .get(i) and .size() methods. The actual list of DOM elements was a separate "private" property of the jQuery object, and you were supposed to use those methods to access its elements and length.
As I worked with that initial jQuery release, it seemed a bit clumsy to have to call .get(i) and .size() to access the elements of the returned jQuery object. This object seemed to be a lot like an array, but you couldn't access its elements the same way as a normal array. So I thought, why not make it act more like a real array with [i] and .length?
It was a fairly simple change to do that, so we ran with it, but we kept the old .get(i) and size() methods for compatibility with code that already used those.
Now a confession: I don't remember the reason for making the return object an array-like object instead of directly inheriting from Array. (It was 11 years ago after all!)
We would have preferred making this object an actual array, but there was a good reason why that would work. Perhaps I will remember after sleeping on it, but in the meantime, this is how we got to the place where the jQuery return object is "array-like" but not a true array.
A jQuery object is a wrapper around an array of DOM elements. So a "jQuery array" is a jQuery object.

.slice.call vs .push in javascript

One of my friends uses [].slice.call() to fill an array with matched elements.
I wonder how this works. I just know the Array.prototype.push to fill an array.
Also I have seen there is a difference in both techniques to fill an array.
So my questions are:
How does Array.prototype.slice help to fill an array?
What are the roles of Array.prototype.slice and Array.prototype.push to make objects and arrays?
Fiddle
var arr=[];
var arr=[].slice.call($('[id^=name]'));
//arr.push($('[id^=name]'))
console.log(arr)
The .slice() method of arrays returns a shallow copy of a portion of an array. It's written as a method on the Array prototype, so the array it operates on is the array in whose context it's invoked. Normally that'd be something like this:
var newArray = oldArray.slice(2, 4);
When you call the .slice() method with .call(), you can control the value of this explicitly. In your friend's code, he's passing a jQuery object as the this value. Because there are no other parameters, .slice() returns a shallow copy of the jQuery object in its entirety, as a new array. (Like some other similar methods, .slice() will work on anything that looks like an array: basically, anything that has a .length property and numerically-indexed properties of interest. A jQuery object fits that description.)
However, since jQuery already has a built-in method to return a plain array of all matched elements, your friend should not bother doing that anymore:
var plainArray = $('[id^=name]').get();
That does exactly the same thing. Using .slice() isn't wrong, but it's kind-of pointless.
How about $('[id^=name]').get()?
The [].slice.call method leverages the array-like length and numeric key properties of jQuery objects to re-use the intentionally generic methods of Array.prototype. The method Array.prototype.slice is documented by the standard to return a new Array object by performing a specific algorithm that accesses numeric-keyed properties in sequence of the this object - regardless of its type - assigning the values to sequential elements of the new Array.
I wouldn't use either approach, because jQuery has get(), which is documented to return an array of the elements matched. Why use a more obscure or less direct approach?
I does't have any specified reason for this case, but The thing i know is, .slice() also used to create another instance of an array, And here the slice add a space to its instance because it have no parameters.
Javascript is the language where you perform a Single operations in 1000's of different ways ! its depend on your choice!
But, We must have to follow the syntax that is made for particular operation.

Which JavaScript Array functions are mutating?

I am writing an Array-derived class in JavaScript and need to know which functions to overload so that I can be aware of changes made to the array.
I know Array.push() and Array.splice() are mutating. Is there a definitive list of any others?
You can find the list on MDN as Mutator methods (along with Accessor and Iteration methods):
copyWithin
fill
pop
push
reverse
shift
sort
splice
unshift
You can also use .concat(), before using your mutation method, to ensure you are not mutating your arrays, eg
const dontMutateMe = [4,5,1,2,3];
const sortArray = dontMutateMe.concat().sort(...)
I found this website called Doesitmutate
Have the list of all functions - and tells whether it mutates or not.

get list of methods in JavaScript's Array

var c=$('<canvas></canvas>')[0].getContext('2d')
for(m in c){console.log(m)}
This prints a list of methods in CanvasRenderingContext2D. How can I do the same for an Array. I want to get "splice", "pop", "push", etc. Obviously for(m in Array.prototype){console.log(m)} won't work.
Most methods and properties of built-in objects are internally marked as non-enumerable, so they will not be enumerated in a for-in loop.
ECMAScript 5 has an Object.getOwnPropertyNames method that returns an array of all property names, so you can do:
Object.getOwnPropertyNames(Array.prototype)
but this isn't supported by all browsers yet.
Do this:
for (m in Array) {
console.log(m)
}
Output:
from
type
implement
extend
alias
mirror
$family
$constructor
pop
push
reverse
shift
sort
splice
unshift
concat
join
slice
indexOf
lastIndexOf
filter
forEach
every
map
some
reduce
reduceRight
each
clone
invoke
clean
associate
link
contains
append
getLast
getRandom
include
combine
erase
empty
flatten
pick
hexToRgb
rgbToHex
overloadSetter
overloadGetter
hide
protect
apply
call
attempt
pass
delay
periodical
create
bind
bindWithEvent
run
I have no idea how to do it with plain js. I usually have underscorejs loaded ant it have an it have a function that returns all the functions of an object
http://documentcloud.github.com/underscore/#functions
You could check underscorejs code to check how they do it.

What does $([]) mean in jQuery?

var username = $("#username"),
password = $("#password"),
allFields = $([]).add(username).add(password);
What is allFields? What is $([])?
Being a newbie to Javascript/jQuery, I've never seen this $([]) notation before and I'm interested in its associated methods.
Given that its "$([])", it's tricky to search for. And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing.
So what is $([])? Can anyone point me to some documentation? I'm interested in learning how to use this strange thing.
The jQuery function accepts an array of DOM nodes.
$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array.
Calling the jQuery function without any arguments returns an empty set. Taken from jQuery docs,
Returning an Empty Set
As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.
So, your example would work the same if you had instead called
$().add(username).add(password);
As other answers have mentioned and the docs say, passing an empty array was required before v 1.4.
[] it's an empty array. Wrapping it with $() overcharges it with jQuery's functions.
In javascript you can create an array this way:
var foo = [];
It is an empty array being passed in the creation of a jQuery object. Presumably to initialize something.
Shouldn't be necessary, at least not in the latest versions of jQuery.
Here's an example without the Array: http://jsfiddle.net/MAzLN/
Works fine, as the alert() shows one element in the object.
jQuery initializes the length property to 0 when the object is created, so I'm not sure what the purpose is, unless it was required in the past.
I believe it creates an empty jQuery collection object.

Categories

Resources