How to convert Object of Arrays to Objects - javascript

I have some data coming from the MVC controller in the below format:
{id: Array[3], city: Array[3]}
I wanted to convert that data into
[Object, Object, Object]
which will have the structure Object0{id, city}, Object1{id, city}, Object2{id, city}
I tried the below method but didnt work out
angular.forEach(data, function(){
vm.Cities = {
id :data.citiesIDs,
city : data.citiesStr
}
});
Can anyone please give me a hint as in where i am going wrong or what is the best way to achieve this. Thanks in advance.

You don't really need Angular for this, plain Javascript works just as well.
function transform(object) {
var result = [];
for (var i = 0; i < object.id.length; i++) {
result.push({
id: object.id[i],
city: object.city[i]
});
}
return result;
}
Then you can call your helper with your data:
var list = transform(data); // <-- list of (id,city) objects
Keep in mind the function assumes both of your id and city arrays are of the same length (which really wouldn't make sense if they weren't), BUT for the case they're not of the same length, you would want to make a minor change in your for loop:
var maxLen = Math.max(object.id.length, object.city.length);
for (var i = 0; i < maxLen; i++)

This is a simple JS operation and here is the demo
// Assuming obj is defined and both obj.id and obj.city are arrays
var obj = {
id: [25, 82, 188, 141],
city: ['Tokyo', 'Munich', 'Los Angeles', 'Sao Paolo'],
};
var max = Math.max(obj.id.length, obj.city.length);
var results = [];
for(var i = 0; i < max; i++) {
var converted = {
id: obj.id[i] ? obj.id[i] : null,
city: obj.city[i] ? obj.city[i] : null
};
results.push(converted);
}
console.log('Coverted array', results);

Very simple example. Iterate over one of the arrays and grab from the other by index.
var cities = []
angular.forEach(data.id, function(id, index) {
var city = {id: id, city: data.city[index]};
cities.push(city);
});

Iterator can help you. e.g.:
var data = {id: [1,2], city: ['Curitiba','São Paulo']};
var array = [];
for(var prop in data){
var length = data[prop].length;
for(var z = 0; z < length; z++){
if(!array.hasOwnProperty(z)){
array[z] = {};
}
array[z][prop] = data[prop][z];
}
}
console.log(array);// [Object{city:'Curitiba',id:1},Object{city:'São Paulo',id:2}]

Related

How can I combine an array of objects with the same keys into one object?

If I start with the following:
var people = [
{id: 9, name: 'Bob', age: 14},
{id: 11, name: 'Joe', age: 15},
{id: 12, name: 'Ash', age: 24}]
What I am trying to get using underscore.js or lodash is a single hash/object with an array of all the values from the collection:
{
id: [9, 11, 12],
name: ['Bob', 'Joe', 'Ash'],
age: [14, 15, 24]
}
Any thoughts?
An answer in straightforward JavaScript code (no libraries):
var result = {};
for (var i = 0; i < people.length; i++) {
var item = people[i];
for (var key in item) {
if (!(key in result))
result[key] = [];
result[key].push(item[key]);
}
}
Here's an alternate plain javascript answer. It's basically the same as Nayuki's but possibly a bit more expressive.
var obj = {};
people.forEach(function(person){
for(prop in person) {
obj[prop] = obj[prop] || [];
obj[prop].push(person[prop]);
}
});
using array.map():
var acc = {};
for (k in people[0]) {
acc[k] = people.map(function (x) {
return x[k]
})
}
fiddle
this solution assumes that all the needed keys will be found in people[0] ...
EDIT:
this is a more extreme version that should catch the keys along the way:
people.reduce(function (ac, item) {
for (k in item) {
if(!ac[k])
ac[k] =[];
ac[k].push(item[k])
}
return ac
}, {})
fiddle2
An alternative that uses Object.keys, Array.prototype.reduce and Array.prototype.map methods:
var res = Object.keys(people[0]).reduce(function(ret, key) {
ret[key] = people.map(function(el) { return el[key]; });
return ret;
}, {});
I don't know javascript much.
But one approach would be to create three arrays, let's say
var id = [];
var name = [];
var age = [];
Then loop through the people array
for(var i=0; i<people.length; i++){
id.push(people[i].id);
name.push(people[i].name);
age.push(people[i].age);
}
Now you have three arrays with respective ids, names and ages
The last step would be to create your final object
var object = {
id:id
name:name
age:age
};

Array of unique JSON values

I'm trying to get an array of unique JSON data based on the comparison of a key value.
In this example, I'm trying to remove any objects with duplicate category values.
Example:
var products = [
{ category: 'fos', name: 'retek' },
{ category: 'fos', name: 'item' },
{ category: 'nyedva', name: 'blabla' },
{ category: 'fos', name: 'gihi' }
];
// array of hold unique values
var uniqueNames = [];
for(i = 0; i< products.length; i++){
if(uniqueNames.indexOf(products[i].category) === -1){
uniqueNames.push(products[i]);
}
}
I'm trying to push to the array any object that doesn't have duplicate category values. Here is a live JSbin.
Please help!
There are several ways to do this, this is one of them: traverse all the items, and filter out the ones which we have already added with that category. For this we use an object to keep which categories we have seen and which ones are new, so we filter only the seen ones:
var seen = {}
var unique = products.filter(function(item){
if(seen.hasOwnProperty(item.category)){
return false;
}else{
seen[item.category] = true;
return true;
}
})
console.log(unique); // only 2 objects
When I am trying to do this, I usually put all of the values into a map as keys, since the map data structure will only allow unique keys. So for this case:
var crops = [ {
id: 0023,
crop: "corn"
},
{
id: 0034,
crop: "corn"
},
{
id: 0222,
crop: "wheat"
}
];
var cropsMap = {};
for(var i = 0; i < crops.length; i++) {
cropsMap[crops[i].crop] = true;
}
var uniqueCrops = Object.keys(cropsMap);
I made a codepen if you want to check it out.
lookup = [];
for (var product, i = 0; product = products[i++];) {
var cat = item.category;
if (!(cat in lookup)) {
lookup[cat] = 1;
result.push(products[cat]);
}
}
Switch
for(i = 0; i< products.length; i++){
if(uniqueNames.indexOf(products[i].category) === -1){
uniqueNames.push(products[i]);
}
}
To
for(i = 0; i< products.length; i++){
if(uniqueNames.indexOf(products[i].category) === -1){
uniqueNames.push(products[i].category); // Push Name of category. Will now not place duplicates into UnqiueNames
}
}
Console
["fos", "nyedva"]

Convert an array of object to array of string?

I'm having an array of object like this-
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
now i want output like this
var string_person = [{sparsh22XYZ},{ankur23},{Richa25ABXabc#xyz.co}];
is their any way to get output like this in javascript, jquery, Angular.js.
Any other web used language is approved.
Check out this jsfiddle. You'll see both Array.prototype.reduce and Array.prototype.map used, both with the same results.
This is classic reduce:
var people = person.reduce(function(agg, p) {
return agg.concat([p.name + p.age + p.address]);
}, []);
The above uses Array.prototype.reduce.
In other words, when you want all the properties of an object or array "reduced" into something, then the most semantic go-to option is probably Array.prototype.reduce in this case.
However, Array.prototype.map can also do the job quite cleanly:
var people = person.map(function(p) {
return p.name + p.age + p.address;
});
This is an argument, now, between readability/complexity vs. semantics.
To limit incidental complexity (in the form of readability), I might go for the map function, even though you could argue this is technically a paradigmatic reduction.
Try this, this method suitable for different object names, it will work good.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23},
{name: 'Richa', age:25, adddress:'ABX', email:'abc#xyz.co'}
];
var result = person.map(function(p){ return Object.keys(p).map(function(k){return p[k]}).join("");})
You can do it like this.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var test = person.map(function(one){
var properties = Object.getOwnPropertyNames(one);
return properties.map(function(prop){
return one[prop];
}).join('');
});
console.log(test);
I think it will help you.
var person = [
{name: 'saprsh', age: 22, address:'XYZ'},
{name: 'Ankur', age: 23, address:'ABC'}
];
var stringarray=[];
// $.each(person, function (i, d) {
// stringarray.push(d.name + d.age + d.address);
// });
//for(var i = 0; i < person.length; i++){
// stringarray.push(person[i].name + person[i].age + person[i].address);
//}
var stringarray = person.map(function(p) {
return p.name + p.age + p.address;
});
console.log(stringarray);
Result: ["saprsh22XYZ", "Ankur23ABC"]
Plz Try this one.
I assume you want a array of strings.
[{sparsh22XYZ},{ankur23ABC}]
is not such an array.
If you want
[ "sparsh22XYZ", "ankur23ABC" ]
you can simply go with
Plain old Javascript:
var string_person = [];
for (var i = 0; i < person.length; i++) {
string_person.push(person[i].name+person[i].age+person[i].address);
}
Underscore.js library
If all you need is a list of values of one of the object properties, it's easiest to go with underscore.js library.
var string_person = _.pluck(person, 'name');
http://underscorejs.org/#pluck
Call the below function on any array of Objects with any number of parameters, it will return you what you want.
function getStringArray(array){
var resultArray = [];
for (i = 0; i < array.length; i++) {
var result = "";
var keysArray = Object.keys(array[i]).sort()
for(j = 0; j < keysArray.length; j++){
result = result+array[i][keysArray[j]];
}
resultArray.push(result);
}
return resultArray;
}
var string_person = [];
for(var i = 0; i < person.length; i++){
string_person.push(person[i].name + person[i].age + person[i].address);
}
Updated:
Also You can use Underscore:
var string_person = _.map(person, function(p){return p.name + p.age + p.address;});
I guess you want to join all members of the object to a string. There are two ways to do this:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
var obj = person[index]; // save the object temporally
person[index] = ''; // place an empty string at the index of the object
// iterate through all members of the object using the "in"-operator
for (var member in obj) {
person[index] += obj[member]; // add the value of the member to the string
}
}
The problem with this technique is, I cannot guarantee that it will join the values of the members in the order you want. It should join them in the order in which the members were defined.
Anyway this solution works fine but only in your case:
// iterate through the array of persons
for (var index = 0; index < person.length; index++) {
// place a string which contains the joined values of the members in the right order at the index of the object
person[index] = [
person[index].name,
person[index].age,
person[index].address
].join('');
}

How to convert arrays into an array of objects

Hi I'm trying to make an array of objects from several arrays.This is probably a very basic question, but I didn't find a proper way of doing it from searching online. :(
The original data I've got is
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
What I want to achieve is an array like :
data = [object1, object2,.....]
Each object is made of :
object1 = {valueYes:15, valueNo:23,valueNotSure:1}
object2 = {valueYes:30, valueNo:75,valueNotSure:-1}
.......
my current code is a bit messy, which only return me an empty value of each key:
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var object1 = Object.create({}, {
myChoice: { value: function(myChoice) {for (var i = 0; i < len; i++){return this.myChoice[i] = myChoice[i];} } }
});
Assuming all your arrays have the same size:
valueYes = [15,30,22,18,2,6,38,18];
valueNo = [23,75,45,12,45,9,17,23];
valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var data = [];
for(var i = 0; i < valueYes.length; i++){
data.push({
valueYes: valueYes[i],
valueNo: valueNo[i],
valueNotSure: valueNotSure[i]
});
}
You could use something like below;
var objs = valueYes.map(function (v, i) {
return {
valueYes: v,
valueNo: valueNo[i],
valueNotSure: valueNotSure[i]
};
});
... this uses the map() Array method, and assumes that all the arrays are the same length...
This?
var valueYes = [15,30,22,18,2,6,38,18];
var valueNo = [23,75,45,12,45,9,17,23];
var valueNotSure = [1,-1,1,1,-1,-1,-1,1];
var data = [];
valueYes.forEach(function(item, index) {
data.push({ valueYes: valueYes[index], valueNo: valueNo[index], valueNotSure: valueNotSure[index] });
});
console.log(data);
http://jsfiddle.net/chrisbenseler/9t1y1zhk/

Javascript transform array into grouped object by value

I have an array:
["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"]
The array can have different sets of cars, and I want to turn it into something like this:
[{
car1: ["car1-coupe"]
},{
car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
car3: ["car3-hatchback", "car3-estate"]
}]
How can I do this in JavaScript or Underscore?
So, assuming an array like this:
var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
You can do this:
var b = a.reduce(function(prev, curr){
var car = curr.split('-')[0]; // "get" the current car
prev[car] = prev[car] || []; // Initialize the array for the current car, if necessary.
prev[car].push(curr); // Add the current item to the array.
return prev;
}, {});
This will return the following object:
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
var result = {};
for (var i = 0; i < array.length; i++) {
var key = array[i].split('-')[0]; // The car we're interested in
if (result[key]) { // Check if this car has already been initialized
result[key].push(array[i]); //add this model to the list
} else {
result[key] = [array[i]]; // initialize the array with the first value
}
}
console.log(result);
/*will return :
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
*/
var myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
var key = arr[i].split("-")[0];
myObj = {};
myObj[key] = [];
for( var j = i; j < arr.length; j+=1 ) {
if( key === arr[j].split("-")[0])
myObj[key].push(arr[j]);
}
myArr.push(myObj);
}
I think this can be done simply with this way. One loop to get the key and another inner loop to get all values of this key.

Categories