Home > Software design >  How to Interpolate JSON Array having template variable with other JSON Object efficiently in JavaScr
How to Interpolate JSON Array having template variable with other JSON Object efficiently in JavaScr

Time:08-31

template = [
  {
    title: "Student 1",
    records: [
      { key: "Roll No", value: "${student1.rollNo}" },
      { key: "Class", value: "${student1.class} standard" },
    ],
  },
    {
    title: "Student 2",
    records: [
      { key: "Roll No", value: "${student2.rollNo}" },
      { key: "Class", value: "${student2.class} standard" },
    ]
  }
];

replacers={
   student1:{
      rollNo:100,
      class:10
   },
   student2:{
      rollNo:101,
      class:12
   }
}

template=[
  {
    title: "Student 1",
    records: [
      { key: "Roll No", value: "100" },
      { key: "Class", value: "10 standard" }
    ],
  },
    {
    title: "Student 2",
    records: [
      { key: "Roll No", value: "101" },
      { key: "Class", value: "12 standard" }
    ]
  }
];

After Interpolate / Mapping JSON array will be like above: (Without using any third party packages)

template=[ { title: "Student 1", records: [ { key: "Roll No", value: "100" }, { key: "Class", value: "10 standard" } ], }, { title: "Student 2", records: [ { key: "Roll No", value: "101" }, { key: "Class", value: "12 standard" } ] } ];

CodePudding user response:

I think this will help you :D

function render(index, item){
    return {
    title: `Student ${index}`,
    records: [
      { key: "Roll No", value: `${item.rollNo}` },
      { key: "Class", value: `${item.class} standard` },
    ],
  }
}

const data=[
   {
      rollNo:100,
      class:10
   },
   {
      rollNo:101,
      class:12
   }
]

const res = data.map( (item, index) => render(index 1, item))

console.log(res)

CodePudding user response:

I have the solution for my problem, is there any efficient way we can get the same result

        title: "Student 1",
        records: [{
                key: "Roll No",
                value: "${student1.rollNo}"
            },
            {
                key: "Class",
                value: "${student1.class} standard"
            },
        ],
    },
    {
        title: "Student 2",
        records: [{
                key: "Roll No",
                value: "${student2.rollNo}"
            },
            {
                key: "Class",
                value: "${student2.class} standard"
            },
        ]
    }
];

const data = {
    student1: {
        rollNo: 100,
        class: 10
    },
    student2: {
        rollNo: 101,
        class: 12
    }
}


var templateString = JSON.stringify(template);

for (var key in data) {
    for (var innerKey in data[key]) {
        if (data[key].hasOwnProperty(innerKey)) {
            var val = data[key][innerKey];
            templateString = templateString.split('${'   key   '.'   innerKey   '}').join(val);
        }
    }
}

template=JSON.parse(templateString);
  • Related