How do I push the keys from an object to an array? - javascript

Suppose I have the following object obj:
obj = {
'key1' : ['1','2','3'],
'key2' : ['1','2','9'],
'key3' : ['1','3','5']
}
How can I transform obj into two arrays that look like the following?
allOfTheKeys = ['key1','key2','key3']
allOfTheArrays = ['1','2','3','5','9']

Something like
allKeys = [];
allElems = [];
for(var k in obj){
allKeys.push(k);
for(var e in obj[k]){
allElem.push(e)
}
}
Actually, in jQuery you can do it more concisely using each() (warning, this isn't tested code):
jQuery.each(obj,function(key){
allKeys.push(key);
jQuery.each(obj[key],function(elem){
allElems.push(elem);
}
});
Okay, you don't want repeats, add in
if(!(elem in allElems)) allElems.push(elem);

As I saw, other answers return repeated values. Here you have the solution (tested):
var allOfTheKeys = [], allOfTheArrays = [], nonRepeatedElems = {};
for(var key in obj){
allOfTheKeys.push(key);
for(var i=0; i< obj[key].length; i++)
nonRepeatedElems[obj[key][i]] = true;
}
for(var e in nonRepeatedElems )
allOfTheArrays.push(e);
If someone's wondering what nonRepeatedElems is, it's a hash table for the array values, whose key is the array element value. So I don't get repeated elements.
If you want your values to be ordered, just call allOfTheArrays.sort(); in the end.
EDIT: #float, Here you have a more understandable solution:
var allOfTheKeys = [], allOfTheArrays = [];
for(var key in obj){
allOfTheKeys.push(key);
for(var i=0; i< obj[key].length; i++){
var arrayElem = obj[key][i];
if(!$.inArray(arrayElem, allOfTheArrays)) //Add to the array if it doesn't exist yet
allOfTheArrays.push(arrayElem);
}
}

Related

How to concatenate values of duplicate keys

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

why Object.keys(data).sort() not work as expected?

I am trying to sort my object keys.
But when I'm printing my object, it always print bb first. Can anyone explain this?
It should print aa first ? I already sorted my keys.
My first key should be aa and then second should be bb.
Here is my code
var data = {
bb:"bb",
aa:"cc"
};
Object
.keys(data)
.sort();
console.log(data)
DEMO
Two things:
objects in JS have no order of elements, like arrays do
Object.keys returns an array of object keys, it does not modify the object itself, see the following example:
var data={bb:"bb",aa:"cc"};
var arr = Object.keys(data);
arr.sort();
console.log(arr); // the array IS modified,
// but it has nothing to do with the original object
try this
var data={bb:"bb",aa:"cc"};
var keys = Object.keys(data);
keys.sort();
var obj = {};
for(i = 0; i < keys.length; i++){
obj[keys[i]] = data[keys[i]];
}
console.log(obj);
There is not any method for sorting object keys in JavaScript but you can do this by a object prototype like this.
Object.prototype.sortKeys = function () {
var sorted = {},
key, a = [];
for (key in this) {
if (this.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = this[a[key]];
}
return sorted;
}
var data = {bb: "bb", aa :"cc"};
alert(JSON.stringify(data.sortKeys())); // Returns sorted object data by their keys

Generate multi dimensional array with key value in javascript

I have an array from json like this:
{"1001":"Account1","1002":"Account2","1003":"Account3"}
and i need convert it to key value format:
[{id:"1001",name:"Account1"},
{id:"1002",name:"Account2"},
{id:"1003",name:"Account3"}]
To do this i wrote this function:
function arrayToMultiArray(list) {
var matrix = [], i;
i = -1;
for (var key in list) {
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
}
return matrix;
}
but the generated array has brackets for each array
[[{id:"1001",name:"Account1"}],
[{id:"1002",name:"Account2"}],
[{id:"1003",name:"Account3"}]]
How can i remove brackets of internal arrays?
You added array in array.
Just change
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
to
matrix.push({"id":key, "name":list[key]});
you are creating a multidimensional array.
remove this
i++;
matrix[i] = [];
and do this directly
matrix.push({"id":key, "name":list[key]});
You could do the same with Object.keys and Array.prototype.map
var obj = {"1001":"Account1","1002":"Account2","1003":"Account3"};
var arr = Object.keys(obj).map(function(key) {
return { id : key, name : obj[key] }
});
console.log(arr);

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

Objects within an Array

I have multiple objects like the one below, and I was wondering what the correct syntax would be for putting them all within a single array. I'm also wondering how to correctly cycle through all of the arrays.
var verbMap = [
{
infinitive: "gehen",
thirdPres: "geht",
thirdPast: "ging",
aux: "ist",
pastPart: "gegangen",
english: "go"
},
{
infinitive: "gelingen",
thirdPres: "gelingt",
thirdPast: "gelang",
aux: "ist",
pastPart: "gelungen",
english: "succeed"
}
];
I know the correct way to cycle through that above array is:
for(v in verbMap){
for(p in verbMap[v]){
}
}
If I wanted to cycle through a larger array holding multiple arrays like verbMap, what would be the correct way to do that?
Just put the verbMap arrays in another array.
var verbMaps = [verbMap1, verbMap2...]
The key thing to understand is that your verbMap is an array of object literals. Only use
for (k in verbMap)...
for object literals.
The correct way to loop thru an array is something like
for (var i = 0; i < verbMaps.length; i++) {
var currentVerbMap = verbMaps[i];
for (var j = 0; j < currentVerbMap.length; j++) {
var currentHash = currentVerbMap[j];
for (var k in currentHash) {
console.log(k, currentHash[k];
}
}
}
The following function outputs every value from a (possibly) infinite array given as a parameter.
function printInfiniteArray(value){
if (value instanceof Array){
for(i=0;i<value.length;i++){
printInfiniteArray(value[i]);
}
} else {
console.log(value);
}
}
Edited code. Thanks jtfairbank
Your array does not contain other arrays. It contains objects. You could try this to loop though it.
for(var i = 0; i < verbMap.length; i++)
{
var obj = verbMap[i];
alert("Object #"+ i " - infinitive: " + obj.infinitive);
}
You would treat the array like any other javascript object.
var arrayOfArrays = [];
var array1 = ["cows", "horses", "chicken"];
var array2 = ["moo", "neigh", "cock-adoodle-doo"];
arrayOfArrays[0] = array1;
arrayOfArrays[1] = array2;
You can also use javascript's literal notation to create a multi-dimentional array:
var arrayOfArrays = [ ["meat", "veggies"], ["mmmm!", "yuck!"] ];
To cycle through the array of arrays, you'll need to use nested for loops, like so:
for (var i = 0; i < arrayOfArrays.length; i++) {
var myArray = arrayOfArrays[i];
for (var j = 0; j < myArray.length; j++) {
var myData = myArray[0]; // = arrayOfArrays[0][0];
}
}
DO NOT USE For...in!!!
That is not what it was made for. In javascript, For...in can have some unwanted behaviors. See Why is using "for...in" with array iteration a bad idea? for more detail.
You can use jQuery.each to cycle through an array or object, without having to check which one it is. A simple recursive function to cycle through key-value pairs in a nested structure, without knowing the exact depth:
var walk = function(o) {
$.each(o, function(key, value) {
if (typeof value == 'object') {
walk(value);
} else {
console.log(key, value);
}
});
}

Categories

Resources