var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
Answer from Darin Dimitrov on Stack Overflowvar list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output
You can create an array of random objects and values using the following code below. First, create an array using where 12 is the length and then the object.
const data = Array.from({
length: 12
}, () => ({
id: Math.floor(Math.random() * (100 - 1)) + 1,
name: Math.random().toString(36).substr(2, 10)
}))
console.log(data)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Try this:
for(var i=0; i<data.length; i++){
console.log(i);
var obj = { "key1": data[i].value1, "key2": data[i].value2};
tableData.push(obj);
}
Pretty straight forward approach to creating an array of objects.
var employees = [];
for (var i = 0; i < 10; i++) {
employees.push({
Column1: 'column 1 of emp' + i,
Column2: 'column 1 of emp' + i
});
}
It's a Old question but just wanna contribute to it. I used Arrays
function car(brand, color, year, price) {
this.brand = brand;
this.color = color;
this.year = year;
this.price = price;
}
var my = new Array();
my.push(new car("Ford", "Black", 2017, 15000));
my.push(new car("Hyundai", "Red", 2017, 17000));
document.getElementById('ford').value = my[0].price;
document.getElementById('hyundai').value = my[1].price;
Ford price: <input type="text" id='ford'/><br><br>
Hyndai price: <input type="text" id='hyundai'/>
To create the structure you mention you can write it in JSON like this:
{
"assignToMap": {
"123": [1, 2, 3, 4],
"345": [1, 2, 3, 4],
"678": [1, 2, 3, 4]
}
}
Although I'm not entirely sure if that's what you're asking here!
I believe you are talking about an associative array. Use the curly braces. This is an array of associative arrays.
var myArray = [
{ myKey1: "myValue1", myKey2: "myValue2", myKey3: "myValue3" },
{ myKey4: "myValue4", myKey5: "myValue5", myKey6: "myValue6" },
{ myKey7: "myValue7", myKey8: "myValue8", myKey9: "myValue9" }
]
This will depend on your content and how you prepare it, but I'd suggest a very generic solution that'll work for any level of nested points. Now, arbitrary nesting doesn't appear to be required in your case, but, hey, nice to have.
Suppose your JSON content is structured like so:
var points = [
{title: "Point", children: [
{title: "Point"},
{title: "Point"},
{title: "Point"},
{title: "Point", children: [
{title: "Point"},
{title: "Point"},
{title: "Point", children: [
// more...?
]}
]}
]}
]
You'll note that you can just keep nesting the points indefinitely.
To render this as HTML, you can use a recursive function. Like this:
function buildList(parentElement, items) {
var i, l, list, li;
if( !items || !items.length ) { return; } // return here if there are no items to render
list = $("<ul></ul>").appendTo(parentElement); // create a list element within the parent element
for(i = 0, l = items.length ; i < l ; i++) {
li = $("<li></li>").text(items[i].title); // make a list item element
buildList(li, items[i].children); // add its subpoints
list.append(li);
}
}
And call it like so:
buildList($("#pageContent").empty(), points);
The point is that since the structure is recursive, it can nest to any depth, but the code is simpler.
Here's a jsfiddle. This is quite a different approach, and Daniel Cook's answer is probably more immediately applicable to you current code, but I thought it worth to point out.
You could also extend it to add the "1", "1.1", "1.2" (and so on) numbers to the titles.
You do not need to add the id to the created li if you store it to a variable.
The code below shows the basic concept. Does it make you more comfortable?
$.each(current.contents, function(_, mp){
var $li = $('<li>' + mp.main + '</li>');
if (mp.subPoints.length){
var $ul =$('<ul>')
$.each(mp.subPoints, function(_, sp){
$ul.append('<li>' + sp + '</li>');
});
$li.append($ul);
}
$pageContent.append($li);
});
Here's a fiddle using the different coding I'm sure this could be improved more. I'm also still learning.
If you only need a flat array (i.e. not multi-dimensional and no arrays within the array), then you can do the following in plain JavaScript:
var strs = [ "String 1", "String 2", "String 3" ];
var list = document.createElement("ul");
for (var i in strs) {
var anchor = document.createElement("a");
anchor.href = "#";
anchor.innerText = strs[i];
var elem = document.createElement("li");
elem.appendChild(anchor);
list.appendChild(elem);
}
Then append list to whichever parent element in the body you desire.
Try this
var str = '<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>';
for(var i in $yourArray){
str += '<li><a href="#">String 1</a></li>';
}
str += '</ul>';
$('body').append(str);
var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
var li = "<li>";
$("ul").append(li.concat(arr[i]))
}
Better yet,
$.each(
a ,
function(i,v) {
$("#target_id").append("<li>" + v + "</li>") ;
}
) ;
Where a is an Array of Objects for the list content, i is the index variable passed to the callback function by jQuery.each ($.each) and vis the value for that index.
For reference: http://api.jquery.com/jQuery.each/ .
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].
I recommend to read the MDN JavaScript Guide.
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [
{"label" : "1", "value" : 12},
{"label" : "1", "value" : 12},
{"label" : "1", "value" : 12},
];
data = [...data, {"label" : "2", "value" : 14}]
console.log(data)
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];
var val = [42,55,51,22];
//Using forEach()
var data = [];
val.forEach((v,i) =>
data= [...data, {"label": lab[i], "value":v}]
)
//Using map()
var dataMap = val.map((v,i) =>
({"label": lab[i], "value":v})
)
console.log('data: ', data);
console.log('dataMap : ', dataMap);
Your code is valid as well, but it creates an object. If you want to use an actual array, it could look like this:
var result = [
{'key1' : value1, 'key2' : value2 },
{'key3' : value3, 'key4' : value4 }
];
Note the change from {} to [] for the outer brackets and the drop of the top-level keys.
Edit
To create such an array dynamically, you can use something like this:
var result = []; // init empty array
result.push( {'key1' : value1, 'key2' : value2 } ); // insert a value
for( var i=0; i<10; i++ ) {
result.push( {'key1' : i, 'key2' : i } ); // insert some more values in a loop
}
The the object you posted is a JS map object,
var result = {
0: {'key1' : value1,'key2' : value2 },
1: {'key3' : value3, 'key4' : value4 }
}
You can access it like you access an associative array.
result[0][key1]
Or this way
result[0].key1
If you need an array of objects
var result = [
{'key1' : value1,'key2' : value2 },
{'key3' : value3, 'key4' : value4 }
];
You can access it like previous example, and in this case you don't need to declare indexes.
Updated:
For map object creation you can also use a loop like @Sirko posted. The only difference is in the values assignation that could be done in this two ways:
var result = {};
result[0] = {'key1' : value1,'key2' : value2 };
result.myOtherObj = {'key1' : value1,'key2' : value2 };
The map contents are the same as
var result = {
0: {'key1' : value1,'key2' : value2 },
myOtherObj: {'key1' : value1,'key2' : value2 }
};