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!! :( ---
});