简体   繁体   中英

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.

输出

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.

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

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM