Insert a new object in Array of object - javascript

I have an Array List.
dataList = []
I want to insert object in array, So I tried this,
dataList.concat([{"name":"BOB", "value":"1"}])
// [{"name":"BOB", "value":"1"}]
but when I insert 2nd object in the same array.
dataList.concat([{"name":"Joe", "value":"2"}])
// [{"name":"Joe", "value":"2"},{"name":"Joe", "value":"2"}]
after inserting second array it replaces first object also.
where am I wrong?, Please help.

Simply use push function
var dataList = [];
dataList.push({
"name": "BOB",
"value": "1"
});
//Pushing second object
dataList.push({
"name": "Joe",
"value": "2"
})
console.log(dataList)

To push a value in an array, you will have to use array.push. array.concat does not adds new item. it merges 2 array and return a third array. So your code:
dataList.concat([{"name":"BOB", "value":"1"}])
does not do anything.
var dataList = []
dataList.concat([{"name":"BOB", "value":"1"}])
console.log(dataList)
As per the behavior, your code should look something like this:
var dataList = []
var obj = [{"name":"BOB", "value":"1"}];
dataList = dataList.concat(obj)
obj[0].value = 2;
dataList = dataList.concat(obj)
console.log(dataList)
The reason both the objects are being affected is because, objects are copied/assigned using reference. So a variable will hold a memory location and any changes to it will be reflected to this location. So if you have more than 1 variable holding this reference, it will also get updated.
So how should you achieve this?
var dataList = []
var obj = {"name":"BOB", "value":"1"};
dataList = dataList.concat(obj)
var obj2 = Object.assign({}, obj)
obj2.value = 2;
dataList = dataList.concat(obj2)
console.log(dataList)
But still using Array.concat is wrong. It is not intended to be used like this.
var dataList = []
var obj = {"name":"BOB", "value":"1"};
dataList.push(obj)
var obj2 = Object.assign({}, obj)
obj2.value = 2;
dataList.push(obj2)
console.log(dataList)
References:
How to append something to an array?
Why does changing an Array in JavaScript affect copies of the array?
How do I correctly clone a JavaScript object?
Object.assign - MDN

Related

how can I add this object in an array?

How can I add {[]} in an array?
#CertainPerformance is correct. You have to have an associated property if you want to have objects.
var a = [ { propertyName : [] } ]
then you can access that array like this :
a[0].propertyName or a[0]['propertyName']
And you can have multiple values inside the object too :
var a = [
{
propertyName_1 : [],
propertyName_2 : "",
propertyName_3 : 3,
}
];
var a = [{}] // no problem, you are assigning an empty object `{}` as first element of array
var a = [[]] // no problem, you are assigning an empty array `[]` as first element of array
var a = [{[]}] // Not working because you're assigning empty array into object
//object needs key to store value
var a = {[]} //Not ok <<======== have you ever see var a = { 1, 2, 3} ?
Please refer to documentation:
An object is a collection of properties, and a property is an association between a name (or key) and a value.

Javascript add elements to an object from another object

I have one object. The first element inside the data object looks like this:
data[0] = {name:"Bob", model:"Tesla", color:"white"};
and a second object, whose first element looks like this:
new_data[0] = {salary:"50000", age:"34"};
data and new_data are the same length, and each element inside of the new_data object needs to be appended onto the correlating data object, to make something like this:
data[0] = {name:"Bob", model:"Tesla", color:"white", salary:"50000", age:"34"};
I've used concat before to add elements into a single line object ( var
people = ["Dan","Bob"];
people.concat("Mike");
, but that same idea doesn't work here:
for ( var i = 0;i<data.length; i++ ) {
data[i] = data[i].concat(new_data[i]);
}
How do I go about looping through this?
As such you have tagged your question with jQuery, I've used its $.extend() method below (jQuery Documentation).
This is just a one liner solution for your case. By passing true to this method, you can easily merge object2 into object1, recursively. jQuery is smart to figure out that both of your objects are array of same length, so the output is an array and each item in the resulting array is a merged result from both objects.
Object.assign is quite new (ES6) and may not be supported in all browsers (Source). But this jQuery way can be a useful time saver for supporting all the browsers.
var collection1 = [{
name: "Bob",
model: "Tesla",
color: "white"
},
{
name: "Bob 1",
model: "Tesla 1",
color: "white 1"
}
];
var collection2 = [{
salary: "50000",
age: "34"
},
{
salary: "50001",
age: "35"
}
];
var result = $.extend(true, collection1, collection2);
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
MDN
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
How do I go about looping through this?
With Object.assign() in mind we can loop through it like below:
var data = [];
data[0] = {name:"Bob", model:"Tesla", color:"white"};
data[1] = {name:"Martin", model:"Ford", color:"Blue"};
data[2] = {name:"Danny", model:"BMW", color:"Purple"};
var new_data =[];
new_data[0] = {salary:"50000", age:"34"};
new_data[1] = {salary:"45000", age:"24"};
new_data[2] = {salary:"10000", age:"39"};
for(var i = 0; i < data.length; i++){
data[i] = Object.assign(data[i], new_data[i]);
console.log(data[i]);
}
You can use jQuery.extend function like shown below. It extends existing data[i] object with properties from new_data[i] object.
for ( var i = 0; i<data.length; i++ ) {
jQuery.extend(data[i], new_data[i]);
}
The most efficient way is to loop through every element in new_data and apply it to data.
for(var key in new_data[0]){
data[0][key] = new_data[0][key];
}
What you need to use if Object.assign like so :
for ( var i = 0;i < data.length; i++ ) {
Object.assign(data[i], new_data[i]);
}
This will alter the content of data.
concat is meant to be used with arrays. It will append one (or more) array(s) at the end of another.
let people = ["Dan","Bob"];
people.concat(["Mike"]); // people is now ["Dan", "Bob", "Mike"]
You could utilize the keys of one of the object to merge the two. This would work in IE9 and up as well. If you need to guard against overriding a property in your base object then you could add a quick truthy check for that key before assigning in the forEach invocation.
var obj1 = {id:1, name: "bob"}
var obj2 = {dob: "2000101"};
Object
.keys(obj1)
.forEach(function(k){
obj2[k] = obj1[k];
});
console.log(obj2);

how to associate key to each individual array and make them key value pair

i have array like this
[["apple","banana"],["monkey"]];
how can i associate key to them like,
[{"fruit":["apple","banana"],"wild":["monkey"]}]
is this possible?
i'm trying something like this
var arr = [["apple","banana"],["monkey"]];
var newArray = [];
for(var i=0;i<arr.length;i++){
newArray["fruit"] = arr[i] //further code i don't know
}
help me th
While you can do that, like this:
var array = [["apple","banana"],["monkey"]];
var update = [
{fruit: array[0], wild: array[1]}
];
console.log(update);
...frankly it seems unlikely that's really want you want.
Very simply you can assign a new name simply
var array = [["apple","banana"],["monkey"]];
var names = ["fruits", "wild"]
var modified = [{names[0]: array[0], names[1]: array[1]}];
If you have a lot of values just use a for loop to iterate and assign value to it.

Iterate through a json object

Here is my object
var myObject = {"HardGood":362,"Music":2};
console.log(myObject[0]); // undefined? instead of "Hardwood 362"
What am I doing wrong?
myObject is an object not an array, so using [0] will indeed be undefined.
Use myObject.HardGood or myObject.Music to get the value or that property
Code
console.log(myObject.HardGood); // will output 362
console.log(myObject.Music); // will output 2
UPDATE
var objects = [
{
"title": "HardGood"
"type": "362"
},
{
"title": "Music"
"type": "2"
}
];
console.log(objects[0].title); // output HardGood
console.log(objects[1].type); // output 2
You should call the first element in an object like this: myObject.key and your key is HardGood.
In arrays it's done like this:
var _Array = [];
_Array .push('x1'); //pushing in array
_Array .push('x2');
console.log(_Array[0]); // getting the first element in that array
Update: if you want to get it dynamically:
var myObject = {"HardGood":362,"Music":2};
for(var key in myObject){
console.log(key +':'+myObject[key]);
}
You have to access JSON object property with . Like below
var myObject = {"HardGood":362,"Music":2};
console.log(myObject.HardGood); //362
Useful links Have a look at below links to understand it better.
Javascript-property-access-dot-notation-vs-brackets
JS-dot-notation-vs-bracket-notation
MDN - OperatorsProperty_Accessors

remove entry from javascript array

I have created an array:
myarray = new Array();
myarray['test_a'] = "test a";
myarray['test_b'] = "test b";
Now I would like to remove the entry with index "test_b". I tried this way:
var del = "test_b";
for(key in myarray){
if(key==del){
myarray.splice(key,1);
}
}
However it does not work. No error. I just checked in firebug the entries for the array and mentioned that "test_b" still exists. What is wrong? Thanks for help.
Arrays are meant to have numeric indices, you want an object, then you can simply use delete:
var obj = {};
obj.test_a = "test a";
obj.test_b = "test b";
var del = "test_b";
delete obj[del];
console.log(obj); //=> { test_a: "test_a" }
splice works on numerical index, what you have is that you have added a property to the array object. You can just do a delete to delete the property from the array object.
delete myarray[del];
Demo
if you are just defining properties on an array and using it just as an object then better consider using an object instead of creating an array to store properties

Categories