0

I have an json array in format as below.

{
  "agents": [{
      "id": "1",
      "first_name": "Stacy",
      "last_name": "Thompson",
      "fields": [{
        "name": "workphone",
        "values": {
          "answer": "8888888888"
        }
      }, {
        "name": "Industry",
        "values": {
          "answer": "computer"
        }
      }]
    },
    {
      "id": "2",
      "first_name": "Jhon",
      "last_name": "Deo",
      "fields": [{
          "name": "workphone",
          "values": {
            "answer": "9999999999"
          }
        },
        {
          "name": "market",
          "values": {
            "answer": "Outer"
          }
        }
      ]
    }
  ]
}

I want to convert it to a simpler array like below, so it will be easier to search :

{
  "agents": [{
    "id": "1",
    "first_name": "Stacy",
    "last_name": "Thompson",
    "workphone": "8888888888",
    "Industry": "computer"
  }, {
    "id": "2",
    "first_name": "Jhon",
    "last_name": "Deo",
    "workphone": "9999999999",
    "market": "Outer"
  }]
}

I wrote the code as below , but I am getting error as

TypeError: Cannot set property 'id' of undefined

Here is the code:

    let temp = response.data.agents;
    let temparray=[];
    for(let i = 0; i < temp.length; i++) {
      let agent = temp[i];
      Object.keys(agent).forEach(function(key) {
          if(key=='fields'){
             let tempfield =  agent.fields;
             for(let j = 0; j < tempfield.length; j++) {
                 let ccs = tempfield[j];
                 Object.keys(ccs).forEach(function(keys) {
                 if(keys=='name'){
                     temparray[i][ccs.name] = ccs.values.answer;
                 }

              });
            }
          }
        else{
         temparray[i][key] = agent[key];
         });
  } 
4
  • 1
    Try Array.prototype.push instead of temparray[i]. The array doesn't have any elements. Commented Jul 20, 2018 at 17:49
  • your expected output is not an array, is an object Commented Jul 20, 2018 at 17:50
  • @CalvinNunes I think she's talking about simplifying the agents array in the object. That is an array. Commented Jul 20, 2018 at 17:53
  • Array.map is simple and powerful. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 20, 2018 at 17:57

4 Answers 4

7

Here's a map and reduce approach using object destructuring to split out the fields in order to reduce then to a flattened object that can be merged with the other properties

data.agents = data.agents.map(({fields, ...rest}) => {
   fields = fields.reduce((a,{name:n,values:v}) => (a[n] = v.answer, a),{});
   return {...rest, ...fields};
});

console.log(data)
<script>
  let data = {
    "agents": [{
        "id": "1",
        "first_name": "Stacy",
        "last_name": "Thompson",
        "fields": [{
          "name": "workphone",
          "values": {
            "answer": "8888888888"
          }
        }, {
          "name": "Industry",
          "values": {
            "answer": "computer"
          }
        }]
      },
      {
        "id": "2",
        "first_name": "Jhon",
        "last_name": "Deo",
        "fields": [{
            "name": "workphone",
            "values": {
              "answer": "9999999999"
            }
          },
          {
            "name": "market",
            "values": {
              "answer": "Outer"
            }
          }
        ]
      }
    ]
  }
</script>

Sign up to request clarification or add additional context in comments.

2 Comments

Saw this after I posted mine. I like that the {...rest} for the properties makes it include the props without having to specify which ones! That's very nice.
you can go all the way {...rest, ...flattenFields(fields)} with the object spread operator
0

Can you try Initializing temparray[i] as object

let tesp =  [{"agents":[ {"id":"1", 
 "first_name":"Stacy", 
 "last_name":"Thompson", 
  "fields":[ {"name":"workphone", "values": {"answer":"8888888888"}},    {"name":"Industry", "values": {"answer":"computer"}}]
 },  {"id":"2", 
"first_name":"Jhon", 
"last_name":"Deo", 
"fields":[ {"name":"workphone", "values": {"answer":"9999999999"}},    {"name":"market", "values": {"answer":"Outer"}}
]
}
]}];
  let temp = tesp; 
  let temparray = []; 
  for (let i = 0; i < temp.length; i++) {
    let agent = temp[i]; 
    Object.keys(agent).forEach(function (key) {
        if (key == 'fields') {
           let tempfield = agent.fields; 
           for (let j = 0; j < tempfield.length; j++) {
               let ccs = tempfield[j]; 
               Object.keys(ccs).forEach(function (keys) {
               if (keys == 'name') {
                   temparray[i][ccs.name] = ccs.pivot.answer; 
               }

            }); 
          }
        }
      else {
          temparray[i] = {};
       temparray[i][key] = agent[key]; 
      }
    }); 
    console.log(temparray);
    }

Comments

0
const newData = data.agents.map((agent) => {
const { first_name, last_name, fields } = agent;
 return {
    first_name,
  last_name,
  workphone: fields[0].values.answer,
  market: fields[1].values.answer,
 }
});
console.log(newData);

Used map to iterate over agents. As map returns a new array, I returned the individual object inside .map

Or you can use the above answer, charlietfl's. If you have dynamic fields.

Comments

0

function convert() {
  let asArray = Object.values( input )[0];
  for( let i in asArray) {
    for( let j in asArray[i].fields ) {
      asArray[i][asArray[i].fields[j].name] = Object.values(asArray[i].fields[j].values).join(',');
    }
    delete asArray[i].fields;
  }
  // console.log(asArray);
  return {'agents': asArray};
}

var input = {
  "agents": [{
      "id": "1",
      "first_name": "Stacy",
      "last_name": "Thompson",
      "fields": [{
        "name": "workphone",
        "values": {
          "answer": "8888888888"
        }
      }, {
        "name": "Industry",
        "values": {
          "answer": "computer"
        }
      }]
    },
    {
      "id": "2",
      "first_name": "Jhon",
      "last_name": "Deo",
      "fields": [{
          "name": "workphone",
          "values": {
            "answer": "9999999999"
          }
        },
        {
          "name": "market",
          "values": {
            "answer": "Outer"
          }
        }
      ]
    }
  ]
};

console.log( convert( input ) );
Desired output:
<pre style="height: 200px; overflow: scroll;">
{
  "agents": [{
    "id": "1",
    "first_name": "Stacy",
    "last_name": "Thompson",
    "workphone": "8888888888",
    "Industry": "computer"
  }, {
    "id": "2",
    "first_name": "Jhon",
    "last_name": "Deo",
    "workphone": "9999999999",
    "market": "Outer"
  }]
}
</pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.