This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 months ago.
I want to build an JSON with name and value like name:"john".
This is my code:
var allFields = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length;i++){
name = inputs[i].name;
item = inputs[i].value;
allFields.push({name: item});
}
var alleFelder = JSON.stringify(allFields);
alert(alleFelder);
My problem is that "name" gets hardcorded into the JSON.
So instead of...:
name:"john",
lastname:"brooks",
birthdate:"1.1.1999"
...im getting:
name:"john",
name:"brooks",
name:"1.1.1999"
You can use this simple function to add new keys with values to your object
const myObj = {}
function addKeyVal(obj, k, v){
obj[k] = v;
}
const keys = ["name", "bday"];
const values = ["Jhon", "1-1-2020"];
for(let i = 0; i < keys.length; i++)addKeyVal(myObj, keys[i], values[i])
console.log(myObj)
I'm looking for the best way to initialize multi-dimensional arrays in Javascript. I'm much more familiar with PHP where I'm not obliged to declare arrays or dimensions before feeding it with values.
Basically what I tried to do is create an array with the following format
catalogue[i]["name"]="a name";
catalogue[i]["description"]="a description";
...etc...
If I do the following:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i]['name']=otherarray[i];
}
Catalogue is undefined, I also tried with catalogue[i].name but same issue. If I only assign a simple value like catalogue[i]=2, it works but that's not what I'm looking for. I couldn't find a working example of what I'm looking for.
Do I need to initialize every possible dimension of an array before being able to feed it with new values?
Thanks
Laurent
var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue[i] = {};
catalogue[i]['name'] = otherarray[i];
}
Or
var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue.push({"name":otherarray[i]});
}
Put this in your loop to create the object you want to store the values in:
catalogue[i] = {}; OR catalogue.push({});
Your code would be like this then:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {}; // initialization
catalogue[i]['name']=otherarray[i];
}
Note that you can initialize and assign a value in the same line:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {
name: otherarray[i],
otherKey: 'otherValue' // list all of your keys and values
};
}
If you want string keys in your array in Javascript you have to declare an Object. The catalogue variable itself is an array but each element inside that array is an object with the two keys "name" and "description". For example this code works :
var c = [1,2,3,4,5];
var n = ['one', 'two', 'three', 'four', 'five'];
var cat = [];
for (i = 0; i < c.length; i++)
{
cat[i] = {
name : n[i],
value: c[i]
};
}
now if you console.dir(cat); it outputs this result :
Array[5]
-> 0 : Object
name: "one"
value: 1
-> 1 : Object
name: "two"
value: 2
...
I have this function:
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
for(var i = 0;i<tareas.length;i++){
var val = new Array(new Date(tareas[i].fecha_registro),tareas[i].porcentaje);
aTar.push(val);
}
console.info(aTar);
},
Using console.info(tareas); print this :
And using console.info(aTar); print :
(The data from tareas always is changing because the data comes from a dropdown)
I need create an new array for each id_usu using the same data , how can I do this?
For example in this case I need an array for id_usu = 4 ( are two id_usu = 4, so i need the data where id_usu = 4) , one array with id_usu = 6 and one array with id_usu = 9
I need do this , because this data are for a chart, so, after , each user ( id_usu ) will be a different color in that chart.
From whatever I have understood form your problem statement and the code you have provided, I've provided a solution below.
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
var idArray = [];
for(var i = 0;i<tareas.length;i++){
if(idArray.indexOf(tareas[i].id_usu) == -1){
var val = new Array(new Date(tareas[i].fecha_registro),
tareas[i].porcentaje);
idArray.push(tareas[i].id_usu);
aTar.push(val);
}
else{
for(var j = 0; j < aTar.length; j++){
if(tareas[i].id_usu == aTar[j][0].id_usu){
aTar[j].length = new Array(new Date(tareas[i].fecha_registro)
,tareas[i].porcentaje);
}
}
}
}
console.info(aTar);
}
I'm using Brute-Force kind of solution, performance can always be increased.
I've created on new array above as idArray to hold the unique id_usus, and am comparing if the current tareas[i].id_usu already is there in that array, if not push the new value to aTar array and tareas[i].id_usu to idArray, else loop over the aTar array and find the array which already has the object with the current tareas[i].id_usu and push the new values at aTar[j].length.
This question already has answers here:
How to put items into grouped arrays where grouped by a particular key
(3 answers)
Closed 9 years ago.
I have a parent object. I want to create child objects from the parent with the same key value pair.
e.g.
parentJSON = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"],
[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"],
[name:"a6",address:"b6",comp:"c3"]}
Now I want to create child objects having same "comp" value.
e.g.
childJSON1 = {[name:"a1",address:"b1",comp:"c1"],
[name:"a2",address:"b2",comp:"c1"]}
childJSON2 = {[name:"a3",address:"b3",comp:"c2"],
[name:"a4",address:"b4",comp:"c2"],
[name:"a5",address:"b5",comp:"c2"]}
childJSON3 = {[name:"a6",address:"b6",comp:"c3"]}
This is what I tried to make it little bit (it will change the parent object with a key indicating number of repetition):
parentJSON = [1,2,3,3,4,4,4,5];
var i=0, x, count, item;
while(i < parentJSON.length) {
count = 1;
item = parentJSON[i];
x = i+1;
while(x < parentJSON.length &&
(x = parentJSON.indexOf(item, x)) != -1) {
count += 1;
parentJSON.splice(x,1);
}
parentJSON[i] = new Array(parentJSON[i],count);
++i;
}
console.log(parentJSON);`
first of all your json is in the incorrect format, it should look like this
[{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}]
An array of objects.
My attempt, also very readable.
var result = {};
$.each(parentJSON, function (i, item) {
if(!result[item.comp]) {
result[item.comp] = [];
}
(result[item.comp]).push(item);
});
alert(JSON.stringify(result))
JsFiddle
First of all your json is actually invalid. You may have an array of objects, but not object which contains an array like that. Also your arrays looks more like objects, because the syntax with the dots is used for objects. Here is how I guess should look like:
var parentJSON = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var child1 = parentJSON.slice(0, 2);
var child2 = parentJSON.slice(2, 5);
And you may use the .slice method to get specific elements of the array.
So..you need to clone objects?
maybe tou can try sth like this:
var sergi= {
name: "sergi",
age: 33
};
var bill = (JSON.parse(JSON.stringify(sergi)));
bill.name = "Bill";
console.log(sergi);
console.log(bill);
parentJSON = function(){
return [
{name:"a1",address:"b1",comp:"c1"},
{name:"a2",address:"b2",comp:"c1"},
{name:"a3",address:"b3",comp:"c2"},
{name:"a4",address:"b4",comp:"c2"},
{name:"a5",address:"b5",comp:"c2"},
{name:"a6",address:"b6",comp:"c3"}
];
}
childJSON1 = new parentJSON().slice(0,2);
childJSON2 = new parentJSON().slice(2,5);
childJSON3 = new parentJSON().slice(5,6);
Try this:
DEMO
var data = [
[{name:"a1",address:"b1",comp:"c1"}],
[{name:"a2",address:"b2",comp:"c1"}],
[{name:"a3",address:"b3",comp:"c2"}],
[{name:"a4",address:"b4",comp:"c2"}],
[{name:"a5",address:"b5",comp:"c2"}],
[{name:"a6",address:"b6",comp:"c3"}]
];
var groups = {};
$.each(data, function(i, item) {
var comp = item.comp;
delete item.comp;
if(groups[comp]) {
groups[comp].push(item);
} else {
groups[comp] = [item];
}
});
var result = $.map(data, function(group, key) {
var obj = {};
obj[key] = group;
return obj;
});
alert(JSON.stringify(groups))
This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
I have this code:
const settings = {
notes: [new musicnote(480,400,"wav/1.wav","cyan",true)],
emiters: [new emiter(300,240), new emiter(340,240)]
}
var notes = [];
var emiters = [];
var LoadLevel = function (level) {
if(settings[level] !== undefined){
currentLevel = level;
notes = settings[level].notes;
emiters = settings[level].emiters;
}
}
And when I change emiters array in game (delete or add some) it does the same to the settings.emiter array. So my question is - how to pass a new array instead of a reference to array in settings object?
You can do that with Array.slice:
var original = [];
var copy = original.slice();
// to test:
copy.push("foo");
alert(original.length); // 0