0

I'm trying to dynamically add an object inside every object which is present in my json array. But I'm unable to do so. My object is getting appended at the end of json which is not what I want.

jsonArray:any=[
    {
        "id": 1000,
        "body": "some comment",
        "postId": 1
    },
    {
        "id": 2,
        "body": "some comment",
        "postId": 1
    },
    {
        "id": 3,
        "body": "some comment",
        "postId": 1
    }
]

selectFLag:any={"selected":"true"}

temArray:any;

learnJSONPArse()
{
    for (var i = 0; this.jsonArray.length > i; i++) 
    {
        Alert(this.jsonArray.length)
    }
}

this.jsonArray.push(this.selectFLag)

-----expected output is

[
    {
        "id": 1000,
        "body": "some comment",
        "postId": 1,
        "selected":"true"
    },
    {
        "id": 2,
        "body": "some comment",
        "postId": 1,
        "selected":"true"
    },
    {
        "id": 3,
        "body": "some comment",
        "postId": 1,
        "selected":"true"
    }
]
computercarguy
  • 2,173
  • 1
  • 13
  • 27
anonymous
  • 1
  • 2
  • Possible duplicate of [Add new attribute (element) to JSON object using JavaScript](https://stackoverflow.com/questions/736590/add-new-attribute-element-to-json-object-using-javascript) – computercarguy Aug 01 '19 at 18:48
  • Try this: `this.sonArray.forEach(x => x.selected = true);` – robert Aug 01 '19 at 18:49
  • Please show a minimal reproduction of the issue you are having with desired input and output. – Keenan Diggs Aug 01 '19 at 18:58
  • @KeenanDiggs desired input [ { "id": 1000, "body": "some comment", "postId": 1 }, { "id": 2, "body": "some comment", "postId": 1 }, { "id": 3, "body": "some comment", "postId": 1 } ] – anonymous Aug 01 '19 at 19:04
  • @KeenanDiggs desired output [ { "id": 1000, "body": "some comment", "postId": 1, "selected":"true" }, { "id": 2, "body": "some comment", "postId": 1, "selected":"true" }, { "id": 3, "body": "some comment", "postId": 1, "selected":"true" } ] – anonymous Aug 01 '19 at 19:05

1 Answers1

0

You're question is a little unclear, but it sounds like you want to map each item in your array to a new item. The new item is the same as the old one, but assigned an additional property.

If so, something like this could work for you:

const objToAppend = { selected: true };
jsonArray.map(item => Object.assign(item, objToAppend));

Refs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Keenan Diggs
  • 2,287
  • 16
  • 17