Evangeline
Evangeline

Reputation: 27

Add values to array using for loop

I know this is pretty simple with php, but in javascript it's harder for me.

I want the output to be as follows:

{
    "data": [
        {
            "id": "1",
            "message": "..."
        },
        {
            "id": "2",
            "message": "..."
        },
        {
            "id": "3",
            "message": "..."
        },
        {
            "id": "4",
            "message": "..."
        },
        {
            "id": "5",
            "message": "..."
        }
    ]
}

I tried this, but it did not as expected.

var data = [];
var array = ["message 1", "message 2", "message 3", "message 4", "message 5"];
array.forEach((messsage, key) => {
    data["data"] = {
        id: key + 1,
        message: messsage
    }
});
console.log(data);

Upvotes: 1

Views: 3856

Answers (3)

ilhan
ilhan

Reputation: 1

Here is an example

var data = [];
var array = ["message 1", "message 2", "message 3", "message 4", "message 5"];
var key=0;
array.forEach((element) => {
key=key+1
data.push({
    "id": key,
    "message": element[key-1]
})
 });
console.log(data);

Upvotes: -1

KooiInc
KooiInc

Reputation: 122906

The data you want is not the data you create. It seems you want to create an Object from an Array, containing one property: data. You can do that in one go, using Array.map.

const data = {
  data: ["message 1", "message 2", "message 3", "message 4", "message 5"]
    .map( (value, index) => ( {id: index + 1, message: value} ) )
};

You can create a more generic function for it:

console.log(createData("message 1", "message 2", "message 3", "message 4", "message 5"));

function createData(...messages) {
  // 'messages' can be an array, or a number of arguments
  messages = messages[0].constructor === Array ? messages[0] : Array.from(messages)
  return {
    data: messages
      .map( (value, index) => ( {id: index + 1, message: value} ) )
  };
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

data["data"] assigns to the property data on the data variable. You should use .map instead, which is more appropriate than forEach when transforming one array into another:

var array = ["message 1", "message 2", "message 3", "message 4", "message 5"];
var data = array.map((message, i) => ({
  id: i + 1,
  message
}));
console.log(data);

If you were to use forEach, the right way to fix your original code would be to push to data on every iteration:

var data = [];
var array = ["message 1", "message 2", "message 3", "message 4", "message 5"];
array.forEach((messsage, key) => {
  data.push({
    id: key + 1,
    message: messsage
  })
});
console.log(data);

Upvotes: 4

Related Questions