I have two objects as follows:
var id="one";
var arrobj = Array[2]
0: Object
name : "a"
desc : "desc1"
1: Object
name : "b"
desc : "desc2"
I am trying to build the object in the following format :
var secondobj = [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]
I tried this :
var secondobj= new Array();
var samplejson = {};
I just gave
samplejson.name = id;
After this I am a bit confused as in how to push values to get the above data structure.
It is a simple as:
samplejson[id]=arrobj;
var arrobj = [{
"name" : "a",
"desc" : "desc1"
},{
"name" : "b",
"desc" : "desc2"
}]
var secondobj = [];
secondobj.push({
one : arrobj
})
console.log(secondobj);
Check this jsfiddle for demo
To make the above structure you can try this:
var secondobj= new Array();
var samplejson = {};
samplejson.one = arrobj;
secondobj.push(samplejson);
console.log(secondobj) // this will give [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]
Related
This question already has answers here:
Group array items using object
(19 answers)
Closed 3 months ago.
I have an array which has keys eventId and selectedNumber. In the array same eventid can be present in multiple objects but selectedNumber value will be always different. My aim is to make a nested array in which each object will have unique eventId But selectedNumber will become an array having numbers from each of those objects having the same eventId. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as eventId. I don't want that. Anyway to do it?
Input:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
Result:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : ["20", "30"]
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
let newarr = []
oldArr.map((x,i)=>{
if(i==0){
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr newarr.push(x)
}else{
if(oldArr[i].eventId == oldArr[i-1].eventId){
const temp = x.selectedNumber
delete x.selectedNumber
newarr[i-1].numArr.push(temp)
}else{
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr
newarr.push(x)
}
}
})
Just reduce your input to an object, and map the object entries to the desired array format:
const input = [{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}];
const result = Object.entries(input.reduce((a, {eventId, selectedNumber}) => {
a[eventId] = a[eventId] || [];
a[eventId].push(selectedNumber)
return a;
}, {})).map(([eventId, selectedNumber]) => ({ eventId, selectedNumber }));
console.log(result);
Instead of creating the intermediate lookup object, you could directly reduce to an array, but it will have a negative impact on the solution's time complexity.
I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}
You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));
You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework
So I have an object I'm trynig to deep extend into - right now the extend function works if the lowest level is just an array, So it looks like this :
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var diff = next.customUrl.filter(function(it) {
return dataEntry.customUrl.indexOf(it) === -1;
});
dataEntry.customUrl = dataEntry.customUrl.concat(diff).sort();
//_.extend(dataEntry, next);
} else {
base.push(next);
}
}
And this works if the object looks like :
[
{"name" : "one", "test" : ["1","2"]},
{"name" : "two", "test" : ["1","2"]}
]
However some things had to change and now the object looks like this :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Where the keys in the array is now an array of objects, and the objects keys are random. So If there was an object with the same key - replace the value (unless its the same, otherwise push a new object inside of there.
So for that object above I would pass this to merge into it for example:
{"name" : "one", "test" : [{"random2" : true}]}
So that would change the value of random2 to true, or something like this
{"name" : "one", "test" : [{"random18" : true}] }
where that would push in random 18 like so :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false},{"random18" : true}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Unsure how to traverse deeper and merge. Thanks for reading!!
Edit : first stab at it -
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var allTags = [];
allTags.push.apply(allTags, dataEntry.customUrl);
allTags.push.apply(allTags, next.customUrl);
dataEntry.customUrl = allTags;
} else {
base.push(next);
}
}
Does not work because it does not cover over objects if they are the same, just pushes into array.
http://jsfiddle.net/p08ayvv8/
this fiddle shows you how jQuery can deal with (deep) extending objects.
See http://api.jquery.com/jquery.extend/ for a detailed explaination.
It is mentionable though that when preforming the second extension jQuery will prepend the old value of test to the array, thats why I added
o1.test = o1.test[0];
I have an object, I want to take a value, for example "title1", what function should I use to solve the problem.
please help me.
[{
total1 : "1200",
total2 : "800",
title1 : "Birth Rate",
title2 : "Death Rate",
year : "2011"
}]
sorry for my mistake..that data is the result from console.log()
The data derived from
$( ".residentgraph" ).each(function(i,el) {
var ids = $(this).attr('id');
var value = $('#'+ids).val();
var dataVal = value.split("/");
chartData.push({
'title1' : dataVal[0],
'title2' : dataVal[1],
'total1' : dataVal[2],
'total2' : dataVal[3],
'year' : dataVal[4]
});
});
I assume that you are having this array in a variable called xArr,
console.log(xArr[0].title1);
DEMO
This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
How to access object using dynamic key? [duplicate]
(3 answers)
Closed 8 years ago.
I need to access object properties with dynamic keys which has persistent structure but different keys, like on one occasion it could be:
var ty_tabs=[{
"key1" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}],
"key2" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}]
}]
and on another one:
var ty_tabs=[{
"key3" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}],
"key4" :[{
"d1" : "v1",
"d2" : "v2",
"d3" : "v3"
}]
}]
How do I adopt my code:
var b,a,d1,d2,d3;
for (b = 0 , a = ty_tabs.length; b < a ; ++b){
d1 = ty_tabs[b].key1[0].d1;
d2 = ty_tabs[b].key1[0].d2;
d3 = ty_tabs[b].key1[0].d3;
}
To access properties with varying keys:
d1 = ty_tabs[b].?[0].d1;
d2 = ty_tabs[b].?[0].d2;
d3 = ty_tabs[b].?[0].d3;
If you don't know about the keys of an object, but need all keys present within an it, you can use Object.keys():
var b,a,d1,d2,d3, i, keys;
for (b = 0 , a = ty_tabs.length; b < a ; ++b){
keys = Object.keys( ty_tabs[b] );
for( i=0; i<keys.length; i++ ) {
d1 = ty_tabs[b][ keys[i] ][0].d1;
d2 = ty_tabs[b][ keys[i] ][0].d2;
d3 = ty_tabs[b][ keys[i] ][0].d3;
}
}
Object.keys() is rather well supported. For older versions of IE, you can use the polyfill provided at MDN