1

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);
1
  • data['data'] should be data[key] - better use map like shown below though Commented Aug 25, 2018 at 6:14

3 Answers 3

4

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

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

1 Comment

It was not what I expected but anyway I solved my problem, thank you
0

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

Comments

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

3 Comments

You should explain what you changed and why and not just write Here is an example.
Foreach wander over the records. Returns each record set of the array. It allows you to do things with Callback. In the example I added messages to the empty Array with Callback.
I ment to extend the answer with an explanation and not to write that as comment. Beside that you changed the answer to something that does not work anymore, and why do now use a key variable you incrment, instead of using the index provided by the forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.