0

I have a result from an api call

var result = [
    {
        "m1": "State"
    },
    {
        "m2": "Occupation"
    },
    {
        "m3": "Qualification"
    },
    {
        "m4": "Salary"
    },
    {
        "m5": "Age"
    },
    {
        "m6": "Status"
    }
]

I want to be able to grab each value with $.each loop but can't seem to figure it out.
Here is my code so far.

var meta = $.parseJSON(result)
$.each(meta, function(index, value){
    console.log(value)
})

The question is how can I log these values "State" and "Occupation", "Qualification", "Salary", "Age" and "Status"?

I know one can't do value."m"+index+1

Please point me the right way.

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • Why do you use an array? Can't you use `var result = {"m1": "State", "m2": "Occupation", ..., "m6": "Status"}` instead? – Heiko Theißen Mar 11 '23 at 10:14
  • 1
    `value["m"+index+1]` should give you the value – cmgchess Mar 11 '23 at 10:16
  • *'I know one can't do `value."m"+index+1`'* but as noted above you can use [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) see [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – pilchard Mar 11 '23 at 11:36

2 Answers2

2

You could take a flat array of all values of nested objects.

const
    data = [{ m1: "State" }, { m2: "Occupation" }, { m3: "Qualification" }, { m4: "Salary" }, { m5: "Age" }, { m6: "Status" }],
    result = data.flatMap(Object.values);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

If you are using js then it will be very easy to iterate values

var result = [
  {
    m1: 'State',
  },
  {
    m2: 'Occupation',
  },
  {
    m3: 'Qualification',
  },
  {
    m4: 'Salary',
  },
  {
    m5: 'Age',
  },
  {
    m6: 'Status',
  },
];

for (var i = 0; i < result.length; i++) {
  //get the key of the object
  var key = Object.keys(result[i])[0];
  //get the value of an object
  var value = result[i][key];
  console.log(value);
}
//jquery
$.each(result, function (index, obj) {
  var key = Object.keys(obj)[0];
  var value = obj[key];
  console.log(value);
});

//dynamic function to iterate array
function iterateArray(array) {
  $.each(array, function (index, obj) {
    $.each(obj, function (key, value) {
      console.log(value);
    });
  });
}

I hope this will be helpful you just need to pass array to this function

pilchard
  • 12,414
  • 5
  • 11
  • 23