Javascript: Add array elements to another array - javascript

I need to split elements in array noted below into 2 separate arrays:
data and labels:
Example using below would look like this:
data: [9, 23, 1, 6]
labels: ['service-1', 'service-2', 'service-3', 'service-4']
Array[16]
. 0: Object
. data: 9
. labels: "service-1"
. __proto__: Object
. 1: Object
. data: 23
. labels: "service-2"
. __proto__: Object
. 2: Object
. data: 1
. labels: "service-3"
. __proto__: Object
. 3: Object
. data: 6
. labels: "service-4"
. __proto__: Object
I'm trying to keep this simple as possible as I've tried several different things that have not worked including reference in this post: add array elements to other,

Try this:
var dataLabels = [
{data: 9, label: "service-1"},
{data: 23, label: "service-2"},
{data: 1, label: "service-3"},
{data: 6, label: "service-4"}
];
var data = [];
var labels = [];
dataLabels.forEach(function(element) {
data.push(element.data);
labels.push(element.label);
});

Assuming your array has a JS object notation, I think this should work:
var data = [];
var labels = [];
for (var i= 0;i<16; i++){
data[i] = array[i].data;
labels[i] = array[i].labels;
}

This should do the trick. Although perhaps a loop will suffice.
var dataLabels = [
{
data: 9,
labels: "service-1"
}, {
data: 23,
labels: "service-2"
}
];
var data = dataLabels.map(function(element) {
return element.data;
});
var labels = dataLabels.map(function(element) {
return element.labels;
});

Related

Parse a Javascript Object into an array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
Okay, so I have a Javascript object that I printout to the console into the following form:
(3) [{…}, {…}, {…}]
0: {data: 50, label: "Active Users"}
1: {data: 20, label: "Expired Users"}
2: {data: 30, label: "Renewed Users"}
length: 3
__proto__: Array(0)
I am trying to extract out the data and label values into separate arrays.
This is what I have done:
var dataObject = doughnutdata;
var obj = JSON.parse(JSON.stringify(dataObject));
console.log(obj);
var labelsdata = [];
var datadummy = [];
labelsdata.push(obj.label);
datadummy.push(obj.data);
console.log(labelsdata);
console.log(datadummy);
But I get [undefined] for both labelsdata and datadummy.
On a sidenote, this is how I have set my doughnutdata:
var doughnutdata = #Html.Raw(Json.Encode(Model.dummysubscribeddata));
Can anyone help me out with this problem?
Thanks.
Try simple loop.
let values = [
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
{data: 50, label: "Active Users"},
];
let data = [];
let label = [];
for(const value of values) {
data.push(value.data);
label.push(value.label);
}
console.log('data: ', data);
console.log('label: ', label);

How to assign a number of properties to an existing object IF that property also has nested properties inside of it?

My data contains an empty object which I would like to populate with properties. Currently it looks like this:
data: function() {
return {
chartData: {}
}
},
Essentially, I want to create this structure:
data: function() {
return {
chartData: {
labels: ["One", "Two"];
datasets: [{
data: ["5", "10"],
label: "Chart"
}]
}
}
}
This like of code successfully adds the labels property and value whilst keeping reactivity, however, I can't figure out how to also add the datasets property which has nested properties itself
this.chartData = Object.assign({}, this.chartData, { labels: ['One', 'Two']})
I figured this one out by reading https://v2.vuejs.org/v2/guide/reactivity.html , however, they haven't shown how to add properties which have nested properties.
Here's one method of building that object using the spread syntax:
// Empty chartData
const chartData = {};
// Your two sets of data
const labels = ['One', 'Two'];
const datasets = { datasets: [{ data: ['5', '10'], label: 'Chart'}] };
// Merge the existing chartData, and labels and datasets together
const newChartData = { chartData: { ...chartData, labels: [...labels], ...datasets } };
console.log(newChartData);

How to map this data to a json array within React?

I have a Rest API which returns data in json of the form :
["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"]
I need the data in this format:
var options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two', clearableValue: false }
];
After fetching the data I am using the following code to map the data in the required format:
if (this.state.coreversions) {
var options = [
this.state.coreversions.map(versions =>
`{ value: '${versions}', label: '${versions}' },`
)
];
}
Here the variable version is equal to a single value of the data returned by the Rest API
Any help would be appreciated.
Array#map returns an array, therefore you do not have to enclose it within square brackets.
Amend your code as follows:
if (this.state.coreversions) {
var options = this.state.coreversions.map(
versions => ({value: versions, label: versions})
);
}
// simplified this.state.coreversions to just coreversions
// only for the purposes of this snippet
var coreversions = ["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"];
if (coreversions) {
var options = coreversions.map(
versions => ({value: versions, label: versions})
);
}
console.log(options);
// logs out an array of objects:
// [
// { value: '1.6.3', label: '1.6.3' },
// { value: '1.6.4', label: '1.6.4' },
// { value: '1.6.5', label: '1.6.5' },
// { value: '1.6.6', label: '1.6.6' },
// { value: '1.7.0', label: '1.7.0' },
// { value: '1.7.2', label: '1.7.2' }
// ]
I think your map function is returning an array of strings instead of objects. Should be like:
return { value: '${versions}', label: '${versions}' }
Note how the above does not have the ticks surrounding the entire line.
React-Select expects an array of objects, not an array of strings.
You can loop through the data, put these values in a object and push it in an array like the following:
var results = ["1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.7.0", "1.7.2"];
var selectData= [];
for (result of results) {
selectData.push({
value: result,
label: result
});
}
console.log(selectData);

How to perform an histogram with the following dictionary?

I have a dictionary called dict that looks as follows:
var dict = {
'Ex': 6,
'C': 6,
'blue': 2,
'car': 2,
'yellow': 2,
'X': 4,
'X3': 2
};
I would like to plot an histogram of it, with the keys as the labels of the horizontal axis and the values of the dictionary that are the frecuency as the vertical axis, I tried:
<canvas id="myChart" width="100" height="100"></canvas>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '# Frecuencies Words',
data: [],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
However the problem is that I am not sure of how to proceed to use the values of the dictionary to perform the graph, I would like to appreciate any suggestion to achieve this, I built the following jsfiddle to explain better the situation: https://jsfiddle.net/xbbc677o/
You're not doing bad, all you need now is to map that object into the data and label fields. Let's begin with labels
Object.keys(dict) returns an array of all the keys from dict
So we put
labels: Object.keys(dict)
Now we need the values for the data array, with Object.keys and map we can do it easily, we use Object.keys to get an array of all the keys in dict and then map to get each value from it's key, like this:
data: Object.keys(dict).map(function (key) { return dict[key]; })
Working fiddle
Both Object.keys and map are part of the ECMAScript 5 specification, so this wont work on ES3 (IE 8 or lower), but you can get pollyfils for both of those functions:
Array.prototype.map polyfill
Object.keys polyfill

How to merge two arrays into one array in angularjs?

This is my code
$scope.studentDetails=[];
$scope.studentDetails=[0][id:101,name:one]
[1][id:102,name:two]
[2][id:103,name:three]
$scope.studentMarks=[];
$scope.studentMarks=[0][id:101,marks:78]
[1][id:102,marks:89]
i have two arrays,first array contains 2 properties like id and name, second array contains two properties like id and marks,i want to concatinate these two arrays into one array.i want to get output like
$scope.studentDetails=[0][id:101,name:one,marks:78]
[1][id:102,name:two,marks:89]
[2][id:103,name:three,marks:null]
Lodash zip() should do that provided your JavaScript is valid in the first place.
$scope.studentDetails = _.zip($scope.studentDetails, $scope.studentMarks);
I got the answer
var newArray = [];
_.each($scope.studentDetails,function(obj))
{
var data=_.findWhere($scope.studentMarks,{"id":obj.id});
if(!_.isUndefined(data))
{
newArray.push({id:obj.id,name:obj.name,marks:data.marks});
}
else
{
newArray.push({id:obj.id,name:obj.name,marks:"null"});
}
}
Hey you can use the push like
$scope.studentDetails.push({'id':'101','name':'one','marks':'78'});
$scope.studentDetails.push({'id':'102','name':'two','marks':'78'});
$scope.studentDetails.push({'id':'103','name':'three','marks':'78'});
using loop you can append like bellow
for(i = 0; i < studentResult.length; i++){
$scope.studentDetails.push(studentResult[i]);
}
For object array _.zip merged two array into single array where each array element also an array.
You can use .map and .extend to create merged object array with _.zip like
var studentDetails = [{ id: 101, name: 'one' }, { id: 102, name: 'two' }, { id: 103, name: 'three' }];
var studentMarks = [{ id: 101, marks: 78 }, { id: 102, marks: 89 }];
var mergedArray = _.zip(studentDetails, studentMarks); //where each element also an array like [ [{ id: 101, name: 'one' }, { id: 101, marks: 78 }] ]
var studentDetails = _.map(mergedArray, function (item) { return _.extend(item[0], item[1]); }); //[{ id: 101, marks: 78, name: 'one' }, ..]

Categories