Home > Back-end >  Get concatened string from variable in javascript object with map function
Get concatened string from variable in javascript object with map function

Time:10-30

I have this object below:

var products = [
        {
           "id":"xxx",
           "name":"AAA"
        },
        {
           "id":"xxx",
           "name":"BBB"
        }
     ];

I´m trying to mapping the object and generate a concatenated string from all the values ´name´ using the map function and then join to concatenate the comma:

var result = products.map(p => Object.values(p.name).join(','));

But I'm getting this output with console.log:

"A,A,A, ,B,B,B"

The is one more comma there and plus it takes each character instead of the full key name value. Am I not accessing the array object in the right way?

CodePudding user response:

I really don't understand your questions but i guess you're trying to concatenate the name values .If Yes,use the below code.

var result = products.map(p => Object.values(p.name).join('')).join('');

CodePudding user response:

Currently you're turning a string into an array and joining each character with a comma between them. You need to move the join outside of the map iterator function. There is also no need for the Object.value() call.

const result = products
  .map((product) => product.name)
  .join(', ')

var products = [
  {
     "id":"xxx",
     "name":"AAA"
  },
  {
     "id":"xxx",
     "name":"BBB"
  }
];

const result = products.map((product) => product.name).join(', ')

document.getElementById('root').innerHTML = result
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use Array.map and Array.join

Logic

  • Create a list of names from products using Array.map.
  • From that list create a string with Array.join

var products = [{"id":"xxx","name":"AAA"},{"id":"xxx","name":"BBB"}];
console.log(products.map(item => item.name).join(','))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related