Add JavaScript object to an existing JavaScript object in for loop - javascript

I am trying to append a JavaScript object to an existing JavaScript object in the loop.
var object1 = { key1: true, header: 'Title A', Size: 100 };
$.each(elements, function (i, item) {
let headerDisplay = '';
headerDisplay = this.title;
var row = { key1: true, header: '' + headerDisplay + '', Size: 100 };
Object.assign(object1, row);
});
I have tried with Object.assign(), but it is giving only the last object.
Expecting output array similar to
var finalObject = [
{ key1: true, header: 'Title A', Size: 100 },
{ key1: true, header: 'Title1', Size: 100 },
{ key1: true, header: 'Title2', Size: 100 },
...
];
Please let me know how can we add objects to an existing one in loop

since you are already using jQuery why not try the $.extend() functionality? it should look something like this:
var object1 = { "key1": true, "header": "Title A", "Size": 100};
$.each(elements, function (i, item) {
let headerDisplay = '';
headerDisplay = this.title;
var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100};
$.extend(object1, row)
});
keep in mind that this method will modify the first object1.
If that is not the intended behavior you could pass an empty object as the first argument of the function and pass the result to another variable like this:
const newObject = $.extend({}, object1, row)
Not sure what you are trying to do but perhaps there are better alternatives to that. Trying to keep a collection of your objects in an array may be another feasible solution. Good luck!!

please try it...:
var object1 = { "key1": true, "header": "Title A", "Size": 100};
var res = [object1];
$.each(elements, function (i, item) {
let headerDisplay = '';
headerDisplay = this.title;
var row = { "key1": true, "header": ""+headerDisplay+"", "Size": 100};
res.push(row);
});
now you have res as finalObj.

Related

JS HighCharts.js Pie data undefined error in code

I am having a bit of an issue with the following code:
//The Code:
var data = [];
for (var i = 0; i < mydata.length; i++) { //looping through data received
var obj = mydata[i]; //current obj in loop
var newObj = { //creating new obj with same structure as the 'data' that works
name: obj.name,
y: obj.subhere.subhere1,
id: i
};
data.push(newObj); //pushing each object into the data array
}
//THE DATA:
var data = [{ name: 'Name 1', y: 20, id: 0 },{ name: 'Name 2', y: 10, id: 1 },{ name: 'Name 3', y: 10, id: 2 }];
//THE CHART CODE:
chart = new Highcharts.Chart({
series:[
{
"data": data,
type: 'pie',
animation: false,
point:{
events:{
click: function (event) {
//alert(this.id);
}
}
}
}
],
"chart":{
"renderTo":"container"
},
});
//The above with create a pie chart with 3 names
//The Data
var mydata =[{
"001":{
"name":"Name 1",
"subhere":{
"subhere1":2
}
},
"002":{
"name":"Name 2",
"subhere":{
"subhere1":20
}
},
}];
The console is giving me the following error:
TypeError: obj.subhere is undefined y: obj.subhere.subhere1,
I can see that the subhere.subhere1 names actually exists so in theory it should not be giving me an error, right?.
How can I fix this issue ... any ideas?
myData doesn't look correctly formatted. It has an extra comma after the bracket before last:
},
}];
You can loop through your object properties:
var data = [];
for (var i = 0; i < mydata.length; i++) { //looping through data received
var obj = mydata[i]; //current obj in loop
for(var key in obj){
var newObj = { //creating new obj with same structure as the 'data' that works
name: obj[key].name,
y: obj[key].subhere.subhere1,
id: i
};
data.push(newObj); //pushing each object
}
}
To work with your existing code, you could change the definition of mydata to this:
var mydata =[
{
"name":"Name 1",
"subhere":{
"subhere1":2
}
},
{
"name":"Name 2",
"subhere":{
"subhere1":20
}
}
];

Modification of array objects

I am trying to rebuild an array ,so I need suggestion on doing it using best practices.
I have an array object as follows:
MainObject:
0:"Namebar"
1: Object
Name: "Title1"
Url: "Url1"
2: Object
Name: "Title2"
Url: "Url2"
3: Object
Name: "Title3"
Url: "Url1"
In the above since the "url" is same , I want to group it same object and I am expecting the output in the following format:
0: "Url1"
1: Object
Name : "Title1"
Url: "Namebar"
2: Object
Name : "Title3"
Url: "Namebar"
1: "Url2"
1: Object
Name : "Title2"
Url: "Namebar"
I am trying to have two arrays and loop through the MainObject for swapping the items which I know is not only a teadious process but very much high on time complexity.
For example like :
var extract1 = MainObject[0];
var extract2 = using for loop to extract and swap ......
I am not getting any other way of achieving this. Any approach for this in javascript/jquery?
This should do the job:
var extract1 = MainObject[0];
var newArray = {};
var newArrProp;
var extract1Props = Object.keys(extract1);
for( i = 0; i< extract1Props.length; i++)
{
newArrProp = extract1Props[i];
var nestedObjects = extract1[newArrProp];
for(j = 0; j < nestedObjects.length; j++)
{
if(!newArray[nestedObjects[j].Url])
{
newArray[nestedObjects[j].Url] = [];
}
newArray[nestedObjects[j].Url].push({Name:nestedObjects[j].Name,Url:newArrProp});
}
}
Working fiddle
You could use some loops.
var MainObject = [{ "Namebar": [{ Name: "Title1", Url: "Url1" }, { Name: "Title2", Url: "Url2" }, { Name: "Title3", Url: "Url1" }] }],
object2 = [];
MainObject.forEach(function (a) {
Object.keys(a).forEach(function (k) {
a[k].forEach(function (b) {
var temp = {};
if (!this[b.Url]) {
temp[b.Url] = [];
this[b.Url] = temp[b.Url];
object2.push(temp);
}
this[b.Url].push({ name: b.Name, Url: k });
}, this);
}, this);
}, Object.create(null));
document.write('<pre>object2 ' + JSON.stringify(object2, 0, 4) + '</pre>');
document.write('<pre>MainObject ' + JSON.stringify(MainObject, 0, 4) + '</pre>');

sorting and pushing objects in an array of objects

sorry for the lack of code — but this is a pretty straight forward javascript question.
I need to sort through an array of objects and push objects with the same key/value pair to a new array.
The objects i'm sorting through are football players. I have all players in an array of objects and want to push each position into their own array.
Ex. each object has a key of "position" so any object with the value of "QB" for the key "position" should be pushed into a new array "Quarterbacks".
What's the right way to sort through objects and push them into a new array that would work for my scenario?
You can use Array.prototype.forEach:
var data = [
{ position: "quarterback", name: "Bob" },
{ position: "center", name: "Jim" },
{ position: "quarterback", name: "Ted" },
];
var dataByPositions = {};
data.forEach(function(x) {
dataByPositions[x.position] = dataByPositions[x.position] || [];
dataByPositions[x.position].push(x);
});
// Demonstration purposes only:
document.body.innerHTML = "<pre>" + JSON.stringify(dataByPositions, null, 4) + "</pre>";
You can create an index object that contains all the positions you've seen so far and then accumulate an array of players for each position:
var data = [
{position: "quarterback", name: "Bob"},
{position: "center", name: "Jim"},
{position: "quarterback", name: "Ted"},
];
var positions = {};
data.forEach(function(item) {
if (!(item.position in positions)) {
positions[item.position] = [];
}
positions[item.position].push(item);
});
log(positions);
function log(x) {
var div = document.createElement("div");
div.innerHTML = JSON.stringify(x);
document.body.appendChild(div);
}
Or you could make this into a generic grouping function like this:
var data = [
{position: "quarterback", name: "Bob"},
{position: "center", name: "Jim"},
{position: "quarterback", name: "Ted"}
];
function groupData(data, key) {
var results = {};
data.forEach(function(item) {
console.log(item);
var value = item[key];
if (!(value in results)) {
results[value] = [];
}
results[value].push(item);
});
return results;
}
log(groupData(data, "position"));
function log(x) {
var div = document.createElement("div");
div.innerHTML = JSON.stringify(x);
document.body.appendChild(div);
}

JSON - array of objects into objects of arrays

I have a series of JSON entries:
[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]
I am trying to convert this array of Objects as painlessly as possible into two objects - one with title name_A, and the second with the title name_B. Objects have to contain the title and an array of matching num-name pairs:
[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]
At first I tried simply to create two objects by reducing the array of object twice, once for name_A and second time for name_B and later glue everything together:
// get 'names' array
var name_A = objArray.reduce(function(memo, curr) {
memo.push({curr.num, curr.name_A})
return memo;
}, []);
But even this is failing. Why there is no push method for memo if I initialize reduce with an empty array?
And second question, am I on a right track or is there a better way to achieve this?
Comments inline, made a few minor corrections to the expectations.
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
// pretty print our output
console.log(JSON.stringify(output, null, " "))
var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]
var output = input.reduce(function (a, b) {
// construct new objects and set their properties
var i = {};
i[b.num] = b.name_A;
var j = {};
j[b.num] = b.name_B;
// add them to our collection elements
a[0].names.push(i);
a[1].names.push(j);
return a;
// initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);
so.log(output)
<pre id="output"></pre>
<script>
var so = {
log: function(o) {
document.getElementById("output").innerHTML = JSON.stringify(o, null, " ")
}
}
</script>
The problem with your code is that { curr.num, curr.name_A } is not a valid object, it's missing the property names. I've added properties num and name in my code below.
var name_A = [];
var name_B = [];
objArray.forEach(function(curr) {
name_A.push({num: curr.num, name: curr.name_a});
name_B.push({num: curr.num, name: curr.name_B});
});
var result = [
{ title: "name_A" }, names: name_A },
( title: "name_B" }, names: name_B }
];
Also, if you want to make an array out of the results of looping over an array, you should use .map rather than .reduce.
Assuming only property num is fixed. All other properties are treated as data, like name_A or name_B.
var a = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }],
result = [];
a.forEach(function (el) {
var num = el.num;
Object.keys(el).forEach(function (k) {
function tryFindIndexAndSetNames(aa, i) {
if (aa.title === k) {
result[i].names[num] = el[k];
return true;
}
}
if (k !== 'num' && !result.some(tryFindIndexAndSetNames)) {
var o = {};
o[num] = el[k];
result.push({ title: k, names: o });
}
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

javascript: truncate object properties in an array

I have an array of objects, say the object looks like following:
var row = {
data: 'test',
text: 'test'
};
I want to loop through the array and just get the object with text property.
What is the best way to do it?
So, I want to loop and the object should look like: row = {text: 'test'}
I tried something like below without luck:
arr.forEach(function (item){ //arr is the array of object
return {text: item.text};
});
Use Array.prototype.map for that:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
return {text: item.data};
});
The result will look like:
[{ text: 'testData' }]
If you want it to be [ {testText: 'testData' }] then:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
var obj = {};
obj[item.text] = item.data;
return obj;
});
As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.
var array = [
{
text : "text",
data : "data"
},
{
text : "text1",
data : "data1"
}
]
var newArray = array.map(function(item){
return item.data;
});
your output will look like
['text','text1']

Categories

Resources