How to create a property in an existing object of an http request?

3

I'm trying to exhaustively put a property on an object that comes from a request (JSON), but I'm not getting it, it's like it just does not get it, but when I do a console.log, there it is, but it's not returning in the reply I send to the postman.

request(url, function (error, response, body) {
    let result = JSON.parse(body);
    result['teste'] = 'teste';
    res.status(200).send(result);
});

Without the property it returns me like this:

[
    {
        "prop1": "prop1",
        "prop2": "prop2",
    },
    {
        "prop1": "prop1",
        "prop2": "prop2",
    },
]

And I wanted the code to return something like this:

[
    {
        "prop1": "prop1",
        "prop2": "prop2",
    },
    {
        "prop1": "prop1",
        "prop2": "prop2",
    },
    "teste": "teste",
]

How do I stay that way up?

    
asked by anonymous 16.05.2018 / 00:22

2 answers

4

You have turned the string into an object.

You need to convert to string again before sending:

request(url, function (error, response, body) {
    let result = JSON.parse(body);
    result['teste'] = 'teste';
    res.status(200).send(JSON.stringify(result));
    //                   ^^^^^^^^^^^^^^
});

Manual:

  

link

    
16.05.2018 / 00:32
0

The API return is an array, to add a new element, use the push .

Example running:

let result = JSON.parse('[{"prop1":"prop1","prop2":"prop2"},{"prop1":"prop1","prop2":"prop2"}]');
result.push({teste: 'teste'});
console.log(JSON.stringify(result));

How are you trying:

let result = JSON.parse('[{"prop1":"prop1","prop2":"prop2"},{"prop1":"prop1","prop2":"prop2"}]');
result['teste'] = 'teste';
console.log(JSON.stringify(result));

This will work if return is an object:

let result = JSON.parse('{"prop1":"prop1","prop2":"prop2"}');
result['teste'] = 'teste';
// ou
result.testeB = 'teste b';
console.log(JSON.stringify(result));
    
17.05.2018 / 10:04