Javascript array insertion - javascript

I have an array in javascript which looks like this:
var arr = [
{ // first
id : '45'
name : 'dsada'
},
{
id : '45'
name : 'dsada'
},
/* ... */
];
I want to add more data to the first index of it, e.g. country:'Egypt'.
Which function should I use?
Or how to push values to specific index in array?
I have used push and splice methods but I can't figure it out.

arr[0].country = 'Egypt'
Set the country property.

Scimonster's answer is correct, but it is better if you take a look to the documentation. Your question highlight some confusion on basics.
Documentation
The Array.prototype.push() method adds one or more elements to the end of an array and returns the new length of the array.
The Array.prototype.splice() method changes the content of an array, adding new elements while removing old elements.
The Object.prototype represents the Object prototype object.

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)

Get object property value

I have an object that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.

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)

Get/find javascript object by its parameter

Considering I have an array of objects, and all objects represent something out of a database, thus they have an unique identifier.
Now I also have the ID and the correct array. How do I search each object in that array where the parameter 'id' equals my ID. (The point is, I don't know the internal identifier for that object. All I have is an ID and I need the entire object for description, last_user, created etc..)
Object
created: "2011-06-08 15:47:11"
description: "Something new.."
id: "1"
last_user: "1"
P.s. I have jQuery embedded, so if there's no default way, a jQuery function would suffice.
$.grep() should do it. In the following example arr is your array of objects. It will find the element that has an id of 1.
var obj = jQuery.grep(arr, function(el, i){
return el.id == 1;
})[0];
You could loop through your array of objects, and check for each one if yourObject.id is equal to the id you are looking for. Then you'll be able to get the other fields, such as yourObject.created

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories