0

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!! :( ---
        });
user1386966
  • 3,302
  • 13
  • 43
  • 72
  • 2
    I guess it is because you are not deep cloning the object. `Object.assign({}, firstItem);` will not deep clone the object but will clone the first level. you could use lodash library which have .clone method for deep cloning... or if the object don't have any function inside it try to clone it using `let tmp = JSON.parse(JSON.stringify(firstItem))` – anees May 25 '20 at 17:07
  • Does this answer your question? [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Heretic Monkey May 25 '20 at 17:14
  • @HereticMonkey thank you for the reference but it didn't as I used Object.assign() I assumed that there will be a cloning of the element thus different references. – user1386966 May 25 '20 at 17:27
  • @AneesIjaz thank you very much! deepClone was the way to do it... !!! – user1386966 May 25 '20 at 17:32

1 Answers1

1

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

Karthik n
  • 61
  • 2