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.
Related
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
I have a server response that comes back as such:
Array[2]
0:Object
user: "Howard",
id:0
1:Object
user: "Robin",
id:1,
myArray: ["mary","john","gary"] // I want to add in here.
]
I then have an array that I created myself. I want to add this array to where an id that === 1 like my example above. I can only imagine I have to use the key of the object that matches id === 1
myArray=["mary","john","gary"]
You can use find to find the object you want, then add the array to it like this:
function addToObject(arr, id, myArr) {
var obj = arr.find(function(o) { // sear inside arr for the object with the id === 1
return o.id === id;
});
if(obj) // if we found an object
obj.myArray = myArr; // add the array myArr as a property to it
}
var arr = [{user: "Howard",id:0}, {user: "Robin",id:1}];
addToObject(arr, 1, ["some", "text"]); // add the array to the object with the id 1
console.log(arr);
Note: I assumed the IDs are unique! So for an ID id there will be ay most one object with that ID.
Hopefully I'm not misunderstanding the question.
just loop through the main array looking for id === 1, then access the myArray property and do what you need.
mainArray.forEach(function(object) {
if(object.id === 1) {
object.myArray = ["mary","john","gary"];
}
}
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
I have an object with dynamic properties. Each of these properties are removed and added based on some events. I want to have a function or property in this object which can return the array of values but having the same reference all the time. Whats the best way to do it?
For e.g if current state of the object is
var obj = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} }
var values = obj.someFunction()
values should be [{ 'name' : 'dark'}]
if current state of obj is
{"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}}
values should be [{ 'name' : 'dark'},{ 'name' : 'magic'}]
The reference of the array and the properties should never change (unless they are deleted).
How about this? It maintains the same array. If you want, you could also mix it in with the object, but would have to add a guard to not also add the function to the values.
var values = someFunction(obj, values);
function someFunction(obj, values) {
values = values || [];
values.length = 0;
for(var key in obj) {
values.push(obj[key]);
}
return values;
}
By the way, clearing the array by setting its length to 0 was gleaned from this post.
My might create a 'meta'-object that stores a reference to the original object and can return the values:
var Values = function(obj) {
this.getValues = function() {
var values = [];
for(i in obj)
values.push(obj[i]);
return values;
};
}
var original = {"410f0ec7bd420d6eafea36bedb716ade" : { 'name' : 'dark'} ,
"f44abc3bb1dad3cd20e97e6a21416830": { 'name' : 'magic'}};
var vals = new Values(original);
var values = vals.getValues();
Given that you seem to be generating the array within "someFunction" (seeing the code of the function and how you attach it to the object would help), you'll need to keep an instance of an array and empty/refill it rather than create a new one. It could be a member of your object (obj.currentItems) or within a closure (depending on how you create it), and it could be updated as you change its properties or on demand within someFunction.
I'll update my answer if you provide more specific code.
Simple question, but I cannot find a solution.
I have an array of objects.
I also have a reference to an object from this array.
I want to delete the object from the array.
How to do it in Javascript (without comparing object properties)?
PS It is easy to do it in C# (using List collection)
List<SomeObject> list = ........ ;
SomeObject element = ......... ;
list.Remove(element);
You can use indexOf to get the index of the object and splice to remove it from the array:
var arr = [ { name: 0}, { name : 1 } , {name : 2 } ];
var myObj = arr[1];
arr.splice(arr.indexOf(myObj),1);
console.log(arr);
There is no way to do this with arrays directly. You will have to find or roll your own implementation of an collection which supports similar operation.