1

I have a javascript object:

[
   {
      "id":"123",
      "name":"abc",
      "email":"[email protected]"
   },
   {
      "id":"465",
      "name":"pqr",
      "email":"[email protected]"
   }
]

I want to concatenate all the names to a single string separated by a comma. I found a solution from https://stackoverflow.com/a/28474201 which concatenates all the keys but I want to concatenate only a specific key

0

4 Answers 4

2

You could map the names and join the array.

var data = [{ id: '123', name: 'abc', email: '[email protected]' }, { id: '465', name: 'pqr', email: '[email protected]' }],
    names = data.map(o => o.name).join(',');

console.log(names);

Sign up to request clarification or add additional context in comments.

Comments

1

Generic solution , you pass any array and you pass the key of the object you want to fetch as comma separated string.

var givenArray = [ { 'id' : '123', 'name' : 'abc', 'email' : '[email protected]' }, { 'id' : '465', 'name' : 'pqr', 'email' : '[email protected]' } ];


function concatKey(data,key){
var result = data.map(obj => obj[key]).join(",");
    return result;
};

console.log(concatKey(givenArray,'name'));

Comments

1

Maybe, if the key is 'name' one possibile solutions is

const data = [ { 'id' : '123', 'name' : 'abc', 'email' : '[email protected]' }, { 'id' : '465', 'name' : 'pqr', 'email' : '[email protected]' } ];

const ret = data.map((el) => {
  return el.name;
}).join(',');

If you want to make dinamically the key

function makeList(key) {        

    const data = [ { 'id' : '123', 'name' : 'abc', 'email' : '[email protected]' }, { 'id' : '465', 'name' : 'pqr', 'email' : '[email protected]' } ];

     return data.map((el) => {
      return el[key];
    }).join(',');
 }

Comments

0

I want to recommend Array.property.reduce(), this is code:

function mergeKey(list = [], key) {
  return list.reduce((acc, cur) => {
      acc += (acc ? ',' : '') + cur[key]
      return acc;
    }, '')
}

//test case
const data = [
  { 'id' : '123', 'name' : 'abc', 'email' : '[email protected]' },
  { 'id' : '465', 'name' : 'pqr', 'email' : '[email protected]' }
];
console.log(mergeKey(data, 'name'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.