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
Related
I have a JSON string that is similar to below:
[
{"id":"112233","region":"UK","city":"London","name":"Company 1"},
{"id":"112244","region":"UK","city":"London","name":"Company 2"},
{"id":"112255","region":"UK","city":"Manchester","name":"Company 3"},
{"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}
]
I am trying to rebuild this into a JS array like this:
[
{
["London"]: [
["112233"] : [{"id":"112233","region":"UK","city":"London","name":"Company 1"}],
["11224"] : [{"id":"112244","region":"UK","city":"London","name":"Company 2"}],
],
["Manchester"]: [
["112255"] : [{"id":"112255","region":"UK","city":"Manchester","name":"Company 3"}],
["112266"] : [{"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}]
]
}
]
Here is the code I am using to do this:
var company = [];
var companies = [];
var cities = [];
// generate citites
for (var i = 0; i < dump.length; i++)
{
// check if city exits
if(!cities.includes(dump[i].city.trim())) {
cities[dump[i].city.trim()] = companies;
}
}
// add companies
for (var i = 0; i < dump.length; i++)
{
company['company_name'] = dump[i].company_name;
company['region'] = dump[i].region;
cities[dump[i].city][dump[i].id] = company;
}
console.log(cities);
Now I get an error stating Cannot set property '112233' of undefined TypeError: Cannot set property '112233' of undefined.
Can someone explain what I'm doing wrong?
The formatting of your desired results is a little strange because you are using [] for what looks like objects with keys. I'm assuming that's a typos and that you really want an object.
Here's a quick easy way to do that with reduce():
let dump = [
{"id":"112233","region":"UK","city":"London","name":"Company 1"},
{"id":"112244","region":"UK","city":"London","name":"Company 2"},
{"id":"112255","region":"UK","city":"Manchester","name":"Company 3"},
{"id":"112266","region":"UK","city":"Manchester","name":"Company 4"}
]
let obj = dump.reduce((obj, item) => {
let city = obj[item.city] || (obj[item.city] = {}) // add city obj to object if not there.
city[item.id] = item // add item.id to city obj
return obj
}, {})
console.log(obj)
EDIT:
The way reduce() works is to start with a value that is passed in the second parameter, here that's an empty object {} that is called obj in the callback, and then iterate through the array (dump). With each iteration we look and see if this obj has a property with the name of the current item in the iteration. If not add it and assign a new object {}. Then with that object in hand, add a property corresponding to item.id and adding the whole item to it.
You could write the entire thing as a for loop, but reduce is pretty succinct — it just takes a while to get used to it.
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.
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 want to create Json like this:
{
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
}
I don't know how to place none-named property in json obj and place and obj into "children".
OK, if you mean key itself is variable then you cannot create json-object in single shot,
you will have to create it using '[]' notation
var myObj = {};
myObj[myProp1] = [] //or some value or some json/map again
myObj[myProp2] = 'hi'
myProp1 and myProp2 are variables.if you can explain your problem in more detail then you will get more clear answer.
If you ask how to manipulate that JSON object, then maybe this would help.
Your original object:
var object = {
"name":"name",
"children":[
{
"childName":"name"
},
{
"childName":"name"
}
]
};
1) How to place none-named property in json obj.
Object is not array, so should assign key/value, though either or both of them were empty. You can insert using dot or like array assignment.
object.country = "Malaysia";
object[""] = "No Keys";
object["novalue"] = "";
2) How to place an obj into "children".
var aNewChild = {
"childName": "Handsome one"
};
object.children.push(aNewChild);
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