push values from array of objects into new array - javascript

I have data such as
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
Now i need output as new
data = [ [1,7],[2,8] ]
My code outputs [1,2,7,8] , i need as [[1,2],[7,8]].
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
//document.write(data.length)
var result = [];
for (var i = 0; i < data.length; ++i) {
var json = data[i];
console.log(json)
for (var prop in json) {
result.push(json[prop]);
console.log(json[prop])
// or myArray.push(json[prop]) or whatever you want
}
}
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

You need to create a nested array in the for loop.
But there's a built-in function Object.values() that will get what you want.
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
var results = data.map(obj => Object.values(obj));
console.log(results);

Object.values() gives you the values in each object. And you need to iterate over an array of objects, so:
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
// data = [ [1,7],[2,8] ]
const extracted = data.map( obj => Object.values(obj))
console.log(extracted)

Object.values()
var data = [{
"2013-01-21": 1,
"2013-01-22": 7
}, {
"2014-01-21": 2,
"2014-01-22": 8
}];
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(Object.values(data[i]));
}
$('#result').html(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

From MDN - The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.
This is exactly what you need.
var data = [{"2013-01-21":1,"2013-01-22":7},{"2014-01-21":2,"2014-01-22":8}];
const arr = data.map(x => Object.values(x));
console.log(arr);

You can get values array by using Object.values()
Solution will be like this:
const data = [{ "2013-01-21": 1, "2013-01-22": 7 }, { "2014-01-21": 2, "2014-01-22": 8 }];
const output = data.map(e => Object.values(e) )
console.log(output)

Related

Is there a way to iterate over an Object based upon the length of an array?

I have this array ["12345678", "87654321"]
And I want to inject each index into an object in the itemId category and loop over the object again placing the second index into another itemId category.
var myArray = ["12345678", "87654321", "12345678"]
var idArray =[]
var arrayLength = myArray.length;
for (var i =0; i < arrayLength; i++) {
let idElement = myArray[i]
idArray.push(idElement);
console.log(idElement);
let multipleitems = {
Request: {
Details: {
id: idArray,
amount: 1
},
}
};
Gives me this output
Request: {Details: {Id: ["12345678", "12345678", "12345678" ], amount: 1}}
Is it possible to iterate over "details however many times based upon how many indexes are in myArray to get this output
{"Request":{"Details":[{"Id":"12345678","amount":1},{"itemId":"87654321","amount":1},{"Id":"12345678","amount":1}]}}
This is a very basic array map() operation. You return a new object every iteration and map() itself returns a new array
var myArray = ["12345678", "87654321", "12345678"];
let multipleitems = {
Request: {
Details: myArray.map(id => ({id, amount:1}) )
}
};
console.log(multipleitems)

Making subarrays from an array algorithm javascript [duplicate]

I have a JavaScript array with 8 elements and some elements are repeating. I want to create separate arrays for identical elements.
example:
original array is [1,1,1,3,3,1,2,2]
resulting arrays will be [1,1,1,1],[3,3],[2,2]
I want a function similar to this:
var array=[1,1,1,3,3,1,2,2];
var createNewArrays=function(array){
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
}
}
};
You could use a hash table as reference to the sub arrays for the collection.
var array = [1, 1, 1, 3, 3, 1, 2, 2],
result = [];
array.forEach(function (a) {
a in this || result.push(this[a] = []);
this[a].push(a);
}, Object.create(null));
console.log(result);
var arr = [1,1,1,3,3,1,2,2];
var hash = Object.create(null);
var result = arr.reduce(function(r, n) {
if(!hash[n]) {
hash[n] = [];
r.push(hash[n]);
}
hash[n].push(n);
return r;
}, []);
console.log(result);
And an ES6 solution that uses Map, and spread:
const arr = [1,1,1,3,3,1,2,2];
const result = [...arr.reduce((r, n) =>
r.set(n, (r.get(n) || []).concat(n)),
new Map()).values()];
console.log(result);
Let's assume you want the resulting arrays to be properties on an object keyed by the value they represent. You just loop through the array, creating or adding to the arrays on the object properties as you go:
var array=[1,1,1,3,3,1,2,2];
var result = {};
array.forEach(function(entry) {
(result[entry] = result[entry] || []).push(entry);
});
console.log(result);
That's a bit dense, here's a clearer version:
var array=[1,1,1,3,3,1,2,2];
var result = {};
array.forEach(function(entry) {
var subarray = result[entry];
if (!subarray) {
subarray = result[entry] = [];
}
subarray.push(entry);
});
console.log(result);

JS failing to populate arrays from array

I have an array of exam result, it contains the date the exam was sat and the grade achieved. I want to put all the grades in one array and the dates in another so I can plot them in a chart.js application. How can I separte them?
Results Array example layout:
Results{
[0] {examDate: "2017-10-16T10:30:00", <ResultEntry>grade: A}
[1] {examDate: "2017-15-16T11:00:00", <ResultEntry>grade: C}
[2] {examDate: "2017-16-16T11:30:00", <ResultEntry>grade: B}
[3]{examDate: "2017-20-16T12:00:00", <ResultEntry>grade: B}
}
But what I try doesn't populate the two new arrays
var dateArray;
var gradeArray;
var counter = 0;
for (members in results) {
dateArray[counter] = members[0];
gradeArray[counter] = members[1];
counter++;//increment storage index
}
I have Jquery installed on my project can the .each functionality be used to achieve this?
You can use map method by passing a callback function.
The map() method creates a new array with the results of calling a provided function(callback) on every element in the calling array.
let results=[{examDate: "2017-10-16T10:30:00", grade: 'A'},{examDate: "2017-15-16T11:00:00", grade: 'C'},{examDate: "2017-16-16T11:30:00", grade: 'B'},{examDate: "2017-20-16T12:00:00", grade: 'B'}];
let dates=results.map(function(a){
return a.examDate;
});
let grades=results.map(function(a){
return a.grade;
});
console.log(dates);
console.log(grades);
You can use also arrow functions.
let grades=results.map(a => a.grade);
You need to get values of fields from array elements. Check this:
var dateArray = [];
var gradeArray = [];
var counter = 0;
for (var member in results) {
dateArray.push(member.examDate);
gradeArray.push(member.grade);
}
If results is an array, then in this line
for (members in results) {
members is basically the index value 0,1,..
so members[0] will be undefined
I have Jquery installed on my project can the .each functionality be
used to achieve this?
Yes, but why not use the native forEach instead
var dateArray = [], gradeArray = [];
results.forEach( function( result ){
dateArray.push( result.examDate );
gradeArray.push( result.grade );
});
Considering that the results array is has the following shape:
let results = [
{ examDate: "2017-10-16T10:30:00", grade: 'A' },
{ examDate: "2017-15-16T11:00:00", grade: 'C' },
{ examDate: "2017-16-16T11:30:00", grade: 'B' },
{ examDate: "2017-20-16T12:00:00", grade: 'B' }
];
Array.prototype.map is perfect for this purpose:
let dateArray = results.map(result => result.examDate);
let gradeArray = results.map(result => result.grade);
You can also loop over the elements in a few different ways:
let dateArray = [],
gradeArray = [];
for (let result of results) {
dateArray.push(result.examDate);
gradeArray.push(result.grade);
}
And a solution similar to yours:
var dateArray = [],
gradeArray = [];
for (var i = 0; i < results.length; i++) {
dateArray[i] = results[i].examDate;
gradeArray[i] = results[i].grade;
}
You can also push them into the array instead of setting a position to the value:
var dateArray = [],
gradeArray = [];
for (var i = 0; i < results.length; i++) {
dateArray.push(results[i].examDate);
gradeArray.push(results[i].grade);
}
And using jQuery each as you mention:
var dateArray = [],
gradeArray = [];
$.each(results , function(i, value) {
dateArray.push(value.examDate);
gradeArray.push(value.grade);
});

Convert set of object's into array item

I have several objects like this:
{'id[0]': 2}
{'url[0]': 11}
{'id[1]': 3}
{'url[1]': 14}
And I want to get something like this:
[{id:2, url:11}, {id:3, url:14}]
Also I have lodash in my project. Maybe lodash have some method for this?
You could use a regular expression for the keys and create a new object if necessary. Then assign the value to the key.
var data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }],
result = [];
data.forEach(function (a) {
Object.keys(a).forEach(function (k) {
var keys = k.match(/^([^\[]+)\[(\d+)\]$/);
if (keys.length === 3) {
result[keys[2]] = result[keys[2]] || {};
result[keys[2]][keys[1]] = a[k];
}
});
});
console.log(result);
This is an ES6 solution based on #NinaScholz solution.
I assume that the objects have only one property each, like the ones presented in the question.
Combine the array of objects to one large object using Object#assign, and convert to entries with Object.entries.
Iterate the array using Array#reduce.
Extract the original key an value from each entry using array
destructuring.
Extract the wanted key and index using a regex and array
destructuring.
Then create/update the new object at the index using object spread.
const data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }];
// combine to one object, and convert to entries
const result = Object.entries(Object.assign({}, ...data))
// extract the original key and value
.reduce((r, [k, value]) => {
// extract the key and index while ignoring the full match
const [, key, index] = k.match(/^([^\[]+)\[(\d+)\]$/);
// create/update the object at the index
r[index] = {...(r[index] || {}), [key]: value };
return r;
}, []);
console.log(result);
var arr = [{'id[0]': 2},
{'url[0]': 11},
{'id[1]': 3},
{'url[1]': 14}];
var result = [];
arr.forEach(function(e, i, a){
var index = +Object.keys(e)[0].split('[')[1].split(']')[0];//get the number inside []
result[index] = result[index] || {}; //if item is undefined make it empty object
result[index][Object.keys(e)[0].split('[')[0]] = e[Object.keys(e)[0]];//add item to object
})
console.log(result);
You can use for loop, .filter(), RegExp constructor with parameter "\["+i+"\]" where i is current index, Object.keys(), .reduce(), .replace() with RegExp /\[\d+\]/
var obj = [{
"id[0]": 2
}, {
"url[0]": 11
}, {
"id[1]": 3
}, {
"url[1]": 14
}];
var res = [];
for (var i = 0; i < obj.length / 2; i++) {
res[i] = obj.filter(function(o) {
return new RegExp("\[" + i + "\]").test(Object.keys(o))
})
.reduce(function(obj, o) {
var key = Object.keys(o).pop();
obj[key.replace(/\[\d+\]/, "")] = o[key];
return obj
}, {})
}
console.log(res);

How to convert JSON data to Array in JQuery?

I am getting Json data from result as following,
var chartData1 = [
{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
]
I want to convert it to following,
var chartData2 = [
['Action', 'value', 'platform'],
['Twitter', '1.00', 2],
['WhatsApp', '1.00', 3],
['Messaging', 'WhatsApp', 4],
]
I have used different methods like parseJSON,map,etc , but i could not get expected results.
Can you help me out from this.
I'm assuming you first need to parse valid JSON string containing your data and then convert each row with object to array. And prepend whole array with array with column names. Following code will exactly do that:
var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";
var chartData = JSON.parse(chartDataString);
var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
row = [];
for (var key in chartData[i]) {
if (i === 0) {
keys.push(key);
}
row.push(chartData[i][key]);
}
if (i === 0) {
data.push(keys);
}
data.push(row);
}
console.log(data);
The following will convert it to an array, providing that it is already parsed as an object.
var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });
console.log(chartData2);
Probably the most ideal here is to map original array to new structure:
var chartData1 = [
{"Action":"Twitter","value":"1.00","platform":"2"},
{"Action":"WhatsApp","value":"1.00","platform":"3"},
{"Action":"Messaging","value":"1.00","platform":"4"}
];
var result = chartData1.map(function(el) {
return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);
alert(JSON.stringify(result, null, 4));

Categories

Resources