How to push data without hardcoding the name [duplicate] - javascript

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)

Related

how to sort and get last value and index in javascript [duplicate]

This question already has answers here:
get key of max value in dictionary nodejs
(2 answers)
Getting key with the highest value from object
(9 answers)
Closed 2 years ago.
i create a let in JavaScript below format
let map={'431':232,'432':123,'433':120}
i want to order the map into following format. order by value.
map={'433':120,'432':123,'431':232}
at last i need to store index and value as numbers.
int1=431 // index as number
int2=232 // values as number
Convert the object to an entries array
Sort it by key (entry[0])
Grab the last entry by index or via Array.prototype.pop()
let map = {'431':232,'432':123,'433':120}
const sorted = Object.entries(map).sort(([ key1 ], [ key2 ]) =>
key2 - key1)
const [ int1, int2 ] = sorted[sorted.length - 1]
console.info(int1, int2)
Use Object.entries, sort them and take the first element (using destructure)
let map = { '431': 232, '432': 123, '433': 120 };
const [[key, value]] = Object.entries(map).sort(([a], [b]) => +a - +b);
console.log(key, value);
it creates your goal object and what you want you can find.
let map={'431':232,'432':123,'433':120}
var keys = [];
var values = [];
for(var k in map) keys.push(parseInt(k));
for(var v in map) values.push(map[v]);
values = values.sort().reverse();
let finalObj=[];
for(i=0;i<keys.length;i++){
let obj = {};
obj[keys[i]] = values[i];
finalObj.push(obj)
}
console.log(finalObj[finalObj.length-1])

Javascript multidimensional array key - val [duplicate]

This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 5 years ago.
In my javascript function i have two single array like this:
var row = ["var1","var2","var3"];
var col = ["res1","res2","res3"];
i would create a multidimensional array like:
[["var1","res1"],["var2","res2"],["var3","res3"]]
i tried:
new Array(m).fill(new Array(n).fill(0));
or solution like:
var dict = [[]];
for (i = 0; i < descendents.length; i++) {
e = descendents[i];
dict[i] = dict[i][e.id]
dict[i] = dict[i][e.value]
}
but the result is not correct for me. i don't know how achieve this
Thanks in advance
Use Array#map to generate a new array based on existing.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
// iterate and generate new array based on row array element
// and fetch element from col using the same index
var res = row.map((v, i) => [v, col[i]]);
console.log(res)
Or with Array.from with a map function.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
var res = Array.from({ length: row.length }, (_, i) => [row[i], col[i]]);
console.log(res)

Create child objects from parent with same property values [duplicate]

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))

Creating arrays in javascript dynamically [duplicate]

This question already has answers here:
Alter and Assign Object Without Side Effects
(7 answers)
Closed 9 years ago.
I'm new in Phonegap app development.
I want to create an array of this type.
var myColumnDefs = [
{id:"id1", name:"name1"},
{id:"id2", name:"name2"},.... ] ;
Please help me how I can do this using javascript.
Because I have to insert data in this coming from webservices.
try this code..
var dataArray = [];
var length = yourjsonAray.length;
for (var i = 0; i < length; i++) {
var obj = {
id: yourjsonAray.keyId[i].id,
name: yourjsonAray.keyName[i].name
};
dataArray.push(obj);
}
Define an array (main array)-
var myColumnDefs = new Array();
and an object
var myObj = new Object();
then in your for loop, simply -
myObj.id = "ID1";
myObj.name = "Name1";
myColumnDefs.push(myObj);
OR, (better way)
function myObj(id, name)
{
this.name = name;
this.id = id;
}
myColumnDefs = new array();
myColumnDefs.push(new myObj("ID1", "Name 1"));
and so on ..

How to in JavaScript or ExtJS: obj['a.b.c'] = 123 => obj.a.b.c = 123? [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 9 years ago.
I need to convert an object with cannonical properties into object with nested properties, splited by '.'
Example:
From:
obj['a.b.c'] = 123;
to:
obj.a.b.c = 123;
Any elegant solutions?
Or maybe there is a solution in ExtJS to make form.getValues() to return an array of fields grouped by names like fieldname[1] or fieldname.1?
Have a look at the private method in ClassManager "createNamespaces". It's essentially what you need to do, except root shouldn't default to global, it should default to your object:
function setValue(o, key, value) {
var root = o,
parts = key.split('.'),
ln = parts.length,
part, i;
for (i = 0; i < ln; i++) {
part = parts[i];
if (typeof part != 'string') {
root = part;
} else {
if (!root[part]) {
root[part] = (i === ln - 1) ? value : {};
}
root = root[part];
}
}
}
var o = {};
setValue(o, 'a.b.c', 123);
console.log(o.a.b.c);

Categories