user1386966
user1386966

Reputation: 3392

Adding new array item to json is overriding all elements with the new value using Typescript

I have a nested json file which I'm trying to modify.

Basic structure:

info: {...}
item: [ {
    name: "somename",
    request: {
         body: {
            mode: "somemode",
            raw:": {\n  \"myTest\": {\n    \"name\": \"myItems\"\n  },\n  ....and so on

I want to duplicate an 'item' and populate the 'raw' keys with some sample values. Seems like everything works fine when changing the name (of the item), but when I try to assign new value to the 'raw' section - it just populates all items of the array with the same value

can you please help to point on my mistake?

my purpose is to create 4 items in my item array, where each has its corresponding 'myTest' value.

import fs from 'fs';
import data from './collections/testCollection.json';
import { raw, json } from 'express';

export class Reader {
    mypath: string;

    constructor(mypath:string) {
        this.mypath = mypath;
    }

    test(): void {
        //console.log(this.mypath);
    }

    readFile(): void {
        var x = data;   #all json data
        var body = data.item; # this is the array of items
        var firstItem = body[0];

        let arrayOfOptionsForRT: string[] = ['items1', 'items2', 'items3', 'items4'];
        arrayOfOptionsForRT.forEach(function(value:string) {
            var tmp = Object.assign({}, firstItem); # trying to clone one full item 
            tmp.name = value #this changes successfully

            var rawbody:string = tmp.request.body.raw;

            var parsedbodyobject = JSON.parse(rawbody);
            console.log('currVal:' + value);
            console.log(parsedbodyobject);
            parsedbodyobject.myTest.name = 'test' + value;

            var newStr = JSON.stringify(parsedbodyobject);
            tmp.request.body.raw = newStr;


            body.push(tmp); # ------ after it is done, all my items get the same name!! :( ---
        });

Upvotes: 0

Views: 163

Answers (1)

Karthik n
Karthik n

Reputation: 61

if u have nested objects (Object.assign({}, firstItem) will not work out. since it will copy the values at first level.so the reference of the second level will be copied.so the mutation happens. As Anees told you can go with 1.lodash library 2.JSON.parse(JSON.stringify(firstItem)) But in option 2 you will lose the functional properties in object if any, For detailed ref see this https://medium.com/@karthikneeliyan/problems-of-object-cloning-in-java-script-883d9e0d92b7

Upvotes: 1

Related Questions