How to update an object property array value? - javascript

If I have an object defined as:
var myObj={};
Then, I update this object with:
myObj['fruit']=['apple', 'orange'];
Later, I would like to append "[banana, melon]" to myObj['fruit'], that's update myObj to
['apple','orange','banana','melon']
what is the most elegant way to update 'fruit' attribute value of myObj in my case? That's update array by appending a new array.
--------EDIT-------
I need a way to append array as one variable, not extract each element of the appended array and push. e.g. oldArray append with newArray = final array

JavaScript has a built in Array.push()
myObj["fruit"].push( 'banana', 'melon' );
There are a few ways to approach appending an array. First up, use apply() to call push with the array as individual arguments:
var toAppend = ['banana', 'melon'];
// note [].push is just getting the "push" function from an empty array
// the first argument to "apply" is the array you are pushing too, the
// second is the array containing items to append
[].push.apply( myObj["fruit"], toAppend );
Also, you could concat() the arrays, however concat doesn't modify the original array so if you have other references they might get lost:
myObj["fruit"] = myObj["fruit"].concat( toAppend );

If you don't want to push, then concat :)

I would suggest to iterate the array items that you want to push, by doing this:
var newObj = ["banana", "melon"];
for (var i in newObj)
{
myObj['fruit'].push(newObj[i]);
}
:)

Related

Why can't array elements use push methods in JavaScript?

var strArr = []
strArr[0].push("someThing Text")
console.log(strArr)
Error: Cannot read properties of undefined (reading 'push')
var strArr = []
strArr[0] = "someThing Text"
console.log(strArr)
Array ["someThing Text"]
What's the difference between the two? Why can't array elements use push methods?
You are trying to push into an array at index 0 inside another array.
var strArr = []
strArr.push("someThing Text")
console.log(strArr)
If you wanted your code to work, you would need to do this.
var strArr = [ [] ] // an array in an array
strArr[0].push("someThing Text")
console.log(strArr)
Simply put, push is an array method. that means it only applies to an array (I look forward to a correction as I am a learner too).
Therefore, push will only apply/operate on an array element if the element is an array as well. Another way to grasp this is to note that elements in an array may be of different data types. Each data type has a different (predefined) set of operations/methods that can be applied to them. push is a predefined method that can be applied only to an array or array element(s) that is/are of the type array.
See the snipped below:
const myArr = ['Hello', 'World', ['Javascript', 'Python', 'PHP'], 100, 'function'];
console.log('Orginal array --> ' + myArr); // Orginal array: Hello,World,Javascript,Python,PHP,100,function
myArr.push(['Vue', 'Angular', 'React']);
console.log('Updated array --> ' + myArr); // Updated array --> Hello,World,Javascript,Python,PHP,100,function,Vue,Angular,React
myArr[2].push('Java');
console.log('Update myArr[2] ' + myArr); // Update myArr[2] Hello,World,Javascript,Python,PHP,Java,100,function,Vue,Angular,React
When you call an array function, you need to call it on the array itself, i.e. strArr.push("someThing Text"). strArr[0] is an array element, and could be a number, string, boolean, or other data type.
You can however add an array element at a specific point in an array, which is sort of what it looks like you were trying to do, with Array.splice(). The parameters are:
index where array element should be inserted
number of items (starting at index) you want to delete
the actual elements you want to insert
var strArr = ["foo", "bar"]
strArr.splice(1, 0, "someThing Text")
console.log(strArr)
You are using the push method on an array element, not the array.
You should use strArr.push()
You are trying to add the element in a specific position using push() method. But the push() method is used to add one or multiple elements to the end of an array. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
array.push(objectName)
var strArr = []
strArr.push("someThing Text")
console.log(strArr)

How can you change the index of multiple array objects?

Problem:
How can you change the index of multiple objects within an array of 100 objects?
In my case I would like to push them to the end of the array.
I have fetched a json array that contains over 100 objects, each with their own properties including a number property for each object that can be used to filter.
Attempts
I tried populating a variable using .splice to remove the specific array objects. Although .push wont accept that variable.
Also tried .slice but couldn't push the sliced objects to the end.
Also tried to loop through the original array using a for loop and an if statement with the condition of each objects "number" property.
Code:
(the fetch is a success, only issue is the restructure of the array itself)
elementsArray.value = await data.json();
let removedElements = elementsArray.value.slice(56,71);
elementsArray.value.push(removedElements);
With slice, the original array will not be modified. Use splice instead.
push accepts one or more elements. so use spread syntax
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
const removedElements = animals.splice(2, 2)
animals.push(...removedElements)
// some other alternatives
// Array.prototype.push.apply(animals, removedElements)
// animals.concat(removedElements)
console.log(animals)
Here is a way you can use splice to append a to b but as in the commentarys mentioned for this use case .concat() or .push(...otherArray) is the better choice
let a = [1,2,3],
b = [4,5,6];
a.splice(0, 0, ...b);
console.log(a);

Javascript syntax: var array = [].push(foo);

Where foo is a defined variable, why is it that the following code:
var array = [].push(foo);
when outputted, equals 1?
From my tests, outputting array will simply output the length of the array.
So the code:
var array = [10,20].push(foo);
would give a value of 3.
As a related question (and to clarify what my code intended to do), why does this not intuitively do what it appears to do, ie:
var array = [];
array.push(foo);
where outputting array gives the expected result of [foo]?
When you use push method it returns length of array. So when you do:
var array = [10,20].push(foo);
you get [10, 20, foo] length of this array is three. But as you say var array it stores returned length from push method in this variable.
Array.prototype.push() always returns the new number of elements in the array. It does not return this instance or a new Array instance. push() is a mutator actually changes the contents of the array.
instead you can try
var array, foo = 30;
(array = [10,20]).push(foo);
console.log(array)
push is a function and it returns an integer representing the length of the array.
Imagine the definition of this function as
int push(object obj);
When you do this:
var array = [].push(foo);
You are actually running the function and returning the value.
Because the return value of push is the new length of the array Documentation and examples.
In your second example, you cited outputting the array, which is going to give you the new array in both cases. However, the returned result of your second case is the new array length as well
var array = [];
array.push(foo); //If you do this in the console, you'll see that 1 gets returned.
console.log(array); //While this will print out the actual contents of array, ie. foo
The definition of push() method including two parts in javascript: Part 1: it adds one or more elements to the end of an array, part 2: it returns the new length of the array.
I think you are missing the part 2 in your understanding of this method.

After using push(), array is logged as a number

I'm trying to get an array of some images to flip through. The first set need to be in descending order, while the second set need to be in ascending order, so I have written this:
var flipArray = [];
function createFlipArray(older, newer){
flipArray = $("#"+older).children();
flipArray = flipArray.get().reverse();
flipArray = flipArray.push($('#'+newer).children());
console.log(flipArray);
loopThroughImages();
}
When I push the second set onto the first set, it logs the array as 4, even though there are 6 items in the whole array.
If I log the array after I populate it with the older children, it returns with HTML objects, which I expect to see after I push the newer children on.
Any suggestions?
.push modifies the array in-place. It does not return a new array, it returns the array's new length.
Array.prototype.push returns the array's new length. It modifies the original array. Remove the flipArray = before it.

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