Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have three json into array like and also i want array[0] with the first json including other jsons nonmatching key with blank value. Please provide me the solution in angular 8

json1 = {name: "Adhikar", email: "adhikar@gmail.com", phoneNumber: "(898) 990-9090", cropType: "rawCrop", cropName: {jawar: true, bajri: false}, cropPeriod: 120}

json2 = {name: "Sagar", email: "sagar@gmail.com", phoneNumber: "", cropType: "", phvalue: 90 }

json3 = {name: "Ajay", email: "ajay@gmail.com", phoneNumber: "", cropType: "rawCrop", cropWeather: "winter"}



so i want to update my array[0] Like this

json1 = {name: "Adhikar", email: "adhikar@gmail.com", phoneNumber: "(898) 990-9090", cropType: "rawCrop", cropName: {jawar: true, bajri: false}, cropPeriod: 120, phvalue:"", cropWeather: ""}

json2 = {name: "Sagar", email: "sagar@gmail.com", phoneNumber: "", cropType: "", phvalue: 90 }

json3 = {name: "Ajay", email: "ajay@gmail.com", phoneNumber: "", cropType: "rawCrop", cropWeather: "winter"}

What I have tried:

getDynamicFormData() {    
    this.dynamicFormResponseService.get(this.id).subscribe(
      res => {
        if (res && res != null) {
          this.dynamicFormData = res;
          const array = [];
          const ids = [];
          this.dynamicFormData.forEach(function (item) {
            if (array[0] == null) {
              array.push(JSON.parse(item.response));
            }
            else {
              var mainArray = JSON.stringify(array[0]);
              for (let key in JSON.parse(mainArray)) {               
                if (JSON.parse(mainArray).hasOwnProperty(key) == JSON.parse(item.response).hasOwnProperty(key)) {
                                  
                }
              }
              console.log(array);
              array.push(JSON.parse(item.response));
              ids.push(item.id);
            }
          });
          this.dynamicFormResponses = array;
          this.dynamicFormResponsesId = ids;
        }
      },
      error => {
        this.toastr.error(error.message);
      }
    );
  }
Posted
Updated 17-Mar-20 0:50am

1 solution

Try something like this:
JavaScript
this.dynamicFormData.forEach(function (item) {
    var parsedItem = JSON.parse(item.response);
    
    if (array.length !== 0) {
        var firstItem = array[0];
        Object.keys(parsedItem).forEach(function(key){
            if (!firstItem.hasOwnProperty(key)) {
                firstItem[key] = "";
            }
        });
    }
    
    array.push(parsedItem);
    ids.push(item.id);
});
Object.keys() - JavaScript | MDN[^]
Object.prototype.hasOwnProperty() - JavaScript | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900