Create an array inside for loop javascript - javascript

I am trying to create a dataset pattern like this from the rest service in my angular application.
Example:
$scope.chartSeries = [
{"name": "Google", "data": [100, 200, 400, 700, 300]},
{"name": "Yahoo", "data": [300, 100, null, 500, 200]},
{"name": "Facebook", "data": [500, 200, 200, 300, 500] },
{"name": "Microsoft", "data": [100, 100, 200, 300, 200] }
];
Right now this is my code to build a similar pattern ,
if (datai){
$rootScope.DashboardData =[];
$rootScope.DashboardData = datai;
var _fieldData = [];
widget.chartConfig.series = [];
widget.chartConfig.series =
$rootScope.DashboardData.map(function(elm) {
return {
name: elm[widget.seriesname],
data:_fieldData.push(elm[widget.dataname])
};
});
}
Problem is data field is not creating an array. This is the final output which the above code generates.
[{"name": "Google", "data": 1}];

push() returns the new array's length
$rootScope.DashboardData.map(function(elm)
{
var _fieldData = [];
_fieldData.push(elm[widget.dataname]);
return { name: elm[widget.seriesname], data: _fieldData };
});
or you can use concat()
return { name: elm[widget.seriesname], data: _fieldData.concat(elm[widget.dataname])};

You are assigning _fieldData.push(elm[widget.dataname]) to data and .push() method returns the new array length, so you need to push the element first and then assign the array itself.
_fieldData.push(elm[widget.dataname])
return { name: elm[widget.seriesname], data:_fieldData};
});

try this , You nee a loop for dataname
$rootScope.DashboardData.map(function(elm)
{
var _fieldData = [];
for(var i=0;i<elm[widget.dataname.length;i++)
{
_fieldData.push(elm[widget.dataname][i]);
}
return { name: elm[widget.seriesname], data: _fieldData
});

Array .push() always returns an new length of an array
You should push that variable into _fieldData.push(elm[widget.dataname]); then assign that variable late in data.
$rootScope.DashboardData.map(function(elm)
{
var _fieldData = [].push(elm[widget.dataname]);
return { name: elm[widget.seriesname], data: _fieldData }
});

Related

Add JavaScript object to an existing JavaScript object in for loop

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.

Logic to Transform data

I have an api that return me data in following format:
[
{
"_id": 1567362600000,
"KIDate": "2019-09-02",
"KITools": [
{
"data": 1,
"tool": "A"
},
{
"data": 2,
"tool": "B"
}
]
},
{
"_id": 1567519839316,
"KIDate": "2019-09-01",
"KITools": [
{
"data": 2,
"tool": "A"
},
{
"data": 1,
"tool": "C"
}
]
},
{
"_id": 1567519839317,
"KIDate": "2019-08-31",
"KITools": [
{
"data": 0,
"tool": "C"
}
]
},
]
I want to transform this data to get the following arrays:
Result 1 - [“2019-09-02”,”2019-09-01”,”2019-08-31”]
Result 2 - [ {name: ‘A’, data:[1, 2, 0] }, { name: 'B', data: [2, 0, 0] }, { name: 'C', data: [0, 1, 0]}]
Currently I am able to achieve this by using loops and per-defining variables with the tool name like following and looping the api data to push into this variable.
var result2 = [{
name: 'A',
data: []
}, {
name: 'B',
data: []
}, {
name: 'C',
data: []
}];
But this is not the expected behavior, the tool names can change and I have to figure that out dynamically based on the data returned by the api.
What is the best way to achieve this without looping like crazy.
You could use reduce method to get the result with array of dates and object of values for each tool.
const data = [{"_id":1567362600000,"KIDate":"2019-09-02","KITools":[{"data":1,"tool":"A"},{"data":2,"tool":"B"}]},{"_id":1567519839316,"KIDate":"2019-09-01","KITools":[{"data":2,"tool":"A"},{"data":1,"tool":"C"}]},{"_id":1567519839317,"KIDate":"2019-08-31","KITools":[{"data":0,"tool":"C"}]}]
const result = data.reduce((r, {KIDate, KITools}, i) => {
r.dates.push(KIDate);
KITools.forEach(({data: dt, tool}) => {
if(!r.values[tool]) r.values[tool] = Array(data.length).fill(0);
r.values[tool][i] = dt
})
return r;
}, {dates: [], values: {}})
console.log(result)
You can use reduce and forEach with Set and Map
Initialize accumulator as object with dates and data key, dates is a Set and data is Map
For every element add the KIDate to dates key,
Loop over KITools, check if that particular too exists in data Map if it exists update it's value by adding current values to id, if not set it's value as per current values
let data = [{"_id": 1567362600000,"KIDate": "2019-09-02","KITools": [{"data": 1,"tool": "A"},{"data": 2,"tool": "B"}]},{"_id": 1567519839316,"KIDate": "2019-09-01","KITools": [{"data": 2,"tool": "A"},{"data": 1,"tool": "C"}]},{"_id": 1567519839317,"KIDate": "2019-08-31","KITools": [{"data": 0,"tool": "C"}]},]
let final = data.reduce((op,{KIDate,KITools})=>{
op.dates.add(KIDate)
KITools.forEach(({data,tool})=>{
if(op.data.has(data)){
op.data.get(data).data.push(tool)
} else{
op.data.set(data, {name: data, data:[tool]})
}
})
return op
},{dates:new Set(),data: new Map()})
console.log([...final.dates.values()])
console.log([...final.data.values()])
The result1 array can be obtained via a direct .map(). To build the result2 array will require additional work - one approach would be to do so via .reduce() as detailed below:
const data=[{"_id":1567362600000,"KIDate":"2019-09-02","KITools":[{"data":1,"tool":"A"},{"data":2,"tool":"B"}]},{"_id":1567519839316,"KIDate":"2019-09-01","KITools":[{"data":2,"tool":"A"},{"data":1,"tool":"C"}]},{"_id":1567519839317,"KIDate":"2019-08-31","KITools":[{"data":0,"tool":"C"}]}];
const result1 = data.map(item => item.KIDate);
const result2 = data.reduce((result, item) => {
item.KITools.forEach(kitool => {
/* For current item, search for matching tool on name/tool fields */
let foundTool = result.find(i => i.name === kitool.tool);
if (foundTool) {
/* Add data to data sub array if match found */
foundTool.data.push(kitool.data);
} else {
/* Add new tool if no match found and init name and data array */
result.push({
name: kitool.tool,
data: [kitool.data]
});
}
});
return result;
}, []).map((item, i, arr) => {
/* Second phase of processing here to pad the data arrays with 0 values
if needed */
for (let i = item.data.length; i < arr.length; i++) {
item.data.push(0);
}
return item;
});
console.log('result1:', result1);
console.log('result2:', result2);

filter data and map the only received data

I am facing a problem.
var arr = ['VBH', 'KTL', 'PVC', 'IF & AF', 'BC', 'CC&HC', 'UBS', 'FAD&DVD'];
var obj = [
{"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0},
{"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0},
{"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0}
];
and I want the result in sorting format as arr variable shows such as VBH object or KTL object if they found.
[
{"materialTypeID":18,"name":null,"abbreviation":"PVC","count":1,"duns":0,"plantId":0},
{"materialTypeID":9,"name":"","abbreviation":"UBS","count":1,"duns":0,"plantId":0},
{"materialTypeID":7,"name":"","abbreviation":"FAD&DVD","count":4,"duns":0,"plantId":0}
]
In java script, I want to implement.
Thanks,
Loop the arr and use filter to get the element from the obj. filter will return a new array, check if the length of this new array is more than 0 , then use push to put the element
var arr = ['VBH', 'KTL', 'PVC', 'IF & AF', 'BC', 'CC&HC', 'UBS', 'FAD&DVD']
var obj = [{
"materialTypeID": 9,
"name": "",
"abbreviation": "UBS",
"count": 1,
"duns": 0,
"plantId": 0
}, {
"materialTypeID": 18,
"name": null,
"abbreviation": "PVC",
"count": 1,
"duns": 0,
"plantId": 0
}, {
"materialTypeID": 7,
"name": "",
"abbreviation": "FAD&DVD",
"count": 4,
"duns": 0,
"plantId": 0
}]
let sortedArray = [];
arr.forEach(function(item) {
let getElem = obj.filter(function(items) {
return items.abbreviation === item
})
if (getElem.length > 0) {
sortedArray.push(getElem[0])
}
})
console.log(sortedArray)
It seems that you want to sort by decreasing materialTypeID.
Your problem has already been resolved there : Javascript object list sorting by object property
obj.sort(function(a, b) {
return b.materialTypeID - a.materialTypeID;
})

Getting values from array of objects

I've got an array of objects
var arr1 = [{
"amount": 700,
"hits": 4,
"day": 1
},
{
"amount": 100,
"hits": 7,
"day": 4
},
{
"amount": 500,
"hits": 3,
"day": 8
}
];
What I need is to create a new array of objects, with key "param" in each object, and the value of "param" should be equals to "amount" field in arr1 objects.
Expected output:
var newArr = [{
"param": 700
},
{
"param": 100
},
{
"param": 500
}
];
You can user Array.prototype.map():
var arr1 = [{"amaunt": 700,"hits": 4,"day": 1}, {"amaunt": 100,"hits": 7,"day": 4}, {"amaunt": 500,"hits": 3,"day": 8}],
newArr = arr1.map(function(elem) {
return {param: elem.amaunt};
});
console.log(newArr);
Try using map:
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var arr2 = arr1.map(function(obj) {
return {param: obj.amaunt};
});
console.log(arr2);
var newArr = []
arr1.forEach(obj => {
newArr.push({param: obj.amount});
});
You can try this
var arr1 = [
{
"amaunt": 700,
"hits":4,
"day":1
},
{
"amaunt": 100,
"hits":7,
"day":4
},
{
"amaunt": 500,
"hits":3,
"day":8
}
];
var newArr=[];
arr1.forEach(function(item){
newArr.push({"param":item.amaunt});
});
console.log(newArr);
Try this
arr1.forEach(function(data){
var obj = {"param": data.amount};
newArr.push(obj);
})
Fiddle here
Another way you can do this
var newArr=[];
arr1.map(function(obj) {
newArr.push("param:"+obj.amaunt);
});

convert json object to specific json array

I have a json object {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } },
and want to convert to json array like this
[ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}]
I can create json object for each index but how can i put those to json array?
for(var abc in objJSON.yAxis)
{
seriesValues += JSON.stringify({name:abc,data:(objJSON.yAxis)[abc]});
}
Any help?
You can just loop through creating the object, don't worry about stringifying it.
var obj = {"yAxis" : { "Batting" : [10, 20, 30, 40] , "Bowling" : [10, 30, 50, 70], "Fielding" : [20, 40, 50, 70] } };
var keys = Object.keys(obj.yAxis),
narray = [];
keys.forEach(function(v) {
narray.push({ "name": v, "data": obj.yAxis[v] });
});
Then, if you need to stringify it, you can simply do a JSON.stringify(narray) later on.
You're close:
var seriesValues = [];
for (var abc in objJSON.yAxis) {
seriesValues.push({name: abc, data: objJSON.yAxis[abc]});
}
That will make a javascript array. If you need it as a JSON string then append:
var myString = JSON.stringify(seriesValues);
Simply stringify after the array generated all around.
var result = [];
for(var name in objJSON.yAxis)
{
result.push({name: name, data: objJSON.yAxis[name]});
}
return JSON.stringify(result);

Categories

Resources