Convert an array of object to array of string? - javascript

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('');
}

Related

Add Dynamic Property To End of Object

I am creating an object and set its properties dynamically and push it to an array, as below:
var modelData = [];
var data = {}
data['rain'] = '123';
var items = [{name: 'prod', default_id: 1}, {name: 'dev', default_id: 2}]
for (var i = 0; i < items.length; i++) {
var id = items[i].name;
data[id] = items[i].default_id;
}
modelData.push(data)
This works fine but by default it adds the properties in ascending order. I want it to be added to the end of the object, so my properties would be rain, prod, dev instead of dev, prod, rain
Is that possible?
see this jsfiddle console for an example.
Objects don't have a guaranteed order in JS. The closest thing you can get is an array of arrays:
var ordered_object = [];
ordered_object.push(['rain', 'First element']);
ordered_object.push(['prod', 'Second element']);
ordered_object.push(['dev', 'Third element']);
ordered_object.forEach(function(pair) {
var key = pair[0],
value = pair[1];
console.log(key + ': ' + value);
});
It will be ordered, but getting the value of a "property" (they're not really properties any more) is a little more difficult:
function get_value(ordered_object, key) {
for (var i = 0; i < ordered_object.length; i++) {
if (ordered_object[i][0] === key) {
return ordered_object[i][1];
}
}
}

How to convert Object of Arrays to Objects

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}]

Combine array items from different properties in a JavaScript object

I'm trying create a function that will iterate an object of arrays, and return one array that concatenates each element from one array to each element in the other arrays:
Object like so:
kitchen = {
food: [".bacon",".bananas"],
drinks: [".soda",".beer"],
apps: ['.fritters','.wings']
}
Desired returned array:
[
".bacon.soda",".bacon.beer",
".bananas.soda",".bananas.beer",
".bacon.fritters",".bacon.wings",
".bananas.fritters",".bananas.wings",
".soda.fritters",".soda.wings",
".beer.fritters",".beer.wings"
]
I'm having difficulty wrapping my brain around how to accomplish this. One thought I had was to create another object and create a hash where each array item becomes a property and then looping through so I have something like:
newObj = {
".bacon": [".soda",".beer",".fritters",".wings"]
".bananas": [".soda",".beer"...etc]
etc...
}
then loop through each prop, concatenating the property on each array element into a new array? Not sure if that's overkill though?
Plain JS is fine, but if you have a coffeescript solution as well that would be great too.
Thanks
Here's a solution that makes use of CoffeeScript syntax (since you asked for a CoffeeScript answer and then deleted that request?):
kitchen =
food: [".bacon",".bananas"]
drinks: [".soda",".beer"]
apps: ['.fritters','.wings']
allGroups = Object.keys(kitchen).map (key) -> kitchen[key]
allValues = []
allGroups.forEach (group, i) ->
otherValues = Array.prototype.concat.apply [], allGroups.slice(i + 1)
group.forEach (v1) -> otherValues.forEach (v2) -> allValues.push(v1 + v2)
console.log(allValues)
Here is the plain JS version:
var kitchen = {
food: [".bacon", ".bananas"],
drinks: [".soda", ".beer"],
apps: ['.fritters', '.wings']
}
var allGroups = Object.keys(kitchen).map(function(key) {
return kitchen[key];
});
var allValues = []
allGroups.forEach(function(group, i) {
var otherValues = Array.prototype.concat.apply([], allGroups.slice(i + 1));
group.forEach(function(v1) {
otherValues.forEach(function(v2) {
allValues.push(v1 + v2);
});
});
});
console.log(allValues)
Try this:
var result = [];
var keys = Object.keys(kitchen);
for (var i = 0; i < keys.length; i++) {
kitchen[keys[i]].forEach(function(ingred1) {
for (var j = i+1; j < keys.length; j++) {
kitchen[keys[j]].forEach(function(ingred2) {
result.push(ingred1 + ingred2);
});
}
});
}
console.log(result);

How to convert my Array of data to key & value pair

I have a array like this.
My Array= PartnerNumber,1044,FirstName,rob,Rank,302
I would like it to be represented as key and value pair
[1]Partner Number - 1044
[2]First Name - rob
[3] rank -302
I would need to post this array data and form a query on my server side control.
Thanks in advance
In modern Web browsers, you can use the very useful array.forEach function:
var array = ["PartnerNumber",1044,"FirstName","rob","Rank",302];
var dictionary = {};
array.forEach(function(item, index) {
if(index % 2 === 0) {
dictionary[item] = array[index + 1];
}
});
document.write("Partner number:" + dictionary.PartnerNumber);
Try it on jsFiddle:
http://jsfiddle.net/6DZvb/
Try this:
var a=["PartnerNumber",1044,"FirstName","rob","Rank",302];
var object={};
for(var i=0;i<a.length;i+=2)
{
object[a[i]]=a[i+1];
}
Then you can access it like,
object["PartnerNumber"]
object["FirstName"]
object["Rank"]
Try this,
var arr=['PartnerNumber',1044,'FirstName','rob','Rank',302];
var newArr={};
for(var i=0,len=arr.length;i<len;i+=2) {
newArr[arr[i]]=(arr[i+1]);
}
console.log(newArr);
obj={};
for(i=0; i<arr.length-1; i=i+2){
obj[arr[i]] = arr[i+1];
}
now if your array is,
arr=[key1,value1,key2,value2,key3,value3];
you will get a new object as,
obj = {key1:value,key2:value2,key3:value3};
Check this working plunk.
Is this what you want? If you open up the console, it will display:
Object { Partner Number: 1044, First Name: "rob", Rank: 302}
EDIT: added code in comment
var myArray = ["PartnerNumber", 1044, "FirstName", "rob", "Rank", 302],
myObj = {};
for (var i = 0; i < myArray.length; i++)
{
if (i % 2 === 0)
myObj[myArray[i].replace(/([A-Z])/g, ' $1').replace(',', '')] = myArray[i + 1];
}
console.log(myObj);

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});

Categories