Home > Net >  Write a string followed by array items as a list
Write a string followed by array items as a list

Time:11-29

I have an array of objects, I want to be able to join it a string followed by having some of those array objects as part of a newly formed ordered list.

My code:

let arr = [
            {
              'message': "message 1",
              'date': "date 1",
              'text': "text 1"
            },
            {
              'message': "message 2",
              'date': "date 2",
              'text': "text 2"
            },
            {
              'message': "message 3",
              'date': "date 3",
              'text': "text 3"
            },
          ];
let new_arr = [];

arr.forEach(d => {
  new_arr.push(`The following messages: ${d.message} at ${d.date}`);
});

console.log(new_arr);

Is there any way I can get the code to do something like this:

The following messages:
    1. message 1 at date 1
    2. message 2 at date 2
    3. message 3 at date 3

CodePudding user response:

let arr = [{"message":"message 1","date":"date 1","text":"text 1"},
           {"message":"message 2","date":"date 2","text":"text 2"},
           {"message":"message 3","date":"date 3","text":"text 3"}]


console.log('The following messages:');
arr.forEach((e,i)=>console.log(`     ${i 1}. ${e.message} at ${e.date}`))

CodePudding user response:

like this?

let arr = [{
    'message': "message 1",
    'date': "date 1",
    'text': "text 1"
  },
  {
    'message': "message 2",
    'date': "date 2",
    'text': "text 2"
  },
  {
    'message': "message 3",
    'date': "date 3",
    'text': "text 3"
  },
];
let result_string = "The following messages:\n\t";
result_string  = arr.map((a, i) => `${i 1}. ${a.message} at ${a.date}`).join("\n\t");
console.log(result_string);

  • Related