You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}.
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}.
You may use:
Array.prototype.map()Array.prototype.reduce()Arrow functionsComma operator
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
Show code snippet
var source = ['left', 'top'];
const result = source.map(value => ({[value]: 0}));
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
Show code snippet
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Maybe you would be better of using an object,
So you could do
var d = {
"Label" : "Value"
};
And to add the value you could
d.label = "value";
This might be a more structured approach and easier to understand if your arrays become big. And if you build the JSON valid it's easy to make a string and parse it back in.
Like var stringD = JSON.stringify(d); var parseD = JSON.parse(stringD);
UPDATE - ARRAY 2D
This is how you could declare it
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]);
And the alert is reading from it,
To add things to it you would say items[0][0] = "Label" ; items[0][1] = "Value";
If you want to do all the labels then all the values do...
for(var i = 0 ; i < labelssize; i ++)
{
items[i][0] = labelhere;
}
for(var i = 0 ; i < labelssize; i ++)
{
items[i][1] = valuehere;
}
You could do like this:
var d = [];
d.push([label, value]);
There are no keys in JavaScript arrays. Use objects for that purpose.
var obj = {};
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
obj[news.title] = news.link;
});
});
// later:
$.each(obj, function (index, value) {
alert( index + ' : ' + value );
});
In JavaScript, objects fulfill the role of associative arrays. Be aware that objects do not have a defined "sort order" when iterating them (see below).
However, In your case it is not really clear to me why you transfer data from the original object (data.news) at all. Why do you not simply pass a reference to that object around?
You can combine objects and arrays to achieve predictable iteration and key/value behavior:
var arr = [];
$.getJSON("displayjson.php",function (data) {
$.each(data.news, function (i, news) {
arr.push({
title: news.title,
link: news.link
});
});
});
// later:
$.each(arr, function (index, value) {
alert( value.title + ' : ' + value.link );
});
This code
var title = news.title;
var link = news.link;
arr.push({title : link});
is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used.
To save an object with two fields you have to do something like
arr.push({title:title, link:link});
or with recent Javascript advances you can use the shortcut
arr.push({title, link}); // Note: comma "," and not colon ":"
If instead you want the key of the object to be the content of the variable title you can use
arr.push({[title]: link}); // Note that title has been wrapped in brackets
var items = [{
'id1': 1,
'id2': 2,
'id3': 3,
'id4': 4
}];
// items[0] is an object
items[0].id5= 5;
console.log(items)
You are trying to use .push() method on an object, that doesn't work.
To get your result you have to add a property to an object.
For more info visit documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
items = [{
'id1': 1,
'id2': 2,
'id3': 3,
'id4': 4
}];
items[0]['id5'] = 5;
console.log(items);
Use .push:
items.push({'id':5});
.push() will add elements to the end of an array.
Use .unshift() if need to add some element to the beginning of array i.e:
items.unshift({'id':5});
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.unshift({'id': 0});
console.log(items);
And use .splice() in case you want to add object at a particular index i.e:
items.splice(2, 0, {'id':5});
// ^ Given object will be placed at index 2...
Demo:
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];
items.splice(2, 0, {'id': 2.5});
console.log(items);
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[prop] = obj[prop];
arr.push(innerObj)
}
}
console.log(arr);
here is demo https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview
p.forEach( function (country) {
country.forEach( function (entry) {
entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
});
});
const data = [{"label": "a", "value": 4}, {"label": "b", "value": 1}, {"label": "c", "value": 2}];
const out = data.map((item, index) => [index + 1, item.value]);
console.log(out);
I hope this is your solution:
const data = [
{
label: 'a',
value: '4'
},
{
label: 'b',
value: '1'
},
{
label: 'c',
value: '2'
},
]
const newArrOfObj = data.reduce((arr, current, index)=> [...arr, {[index+1]:current.value}], []);
console.log(newArrOfObj) //[ { 1: '4' }, { 2: '1' }, { 3: '2' } ]