Dave
Dave

Reputation: 1277

Organizing object arrays

our team has a question about organizing object arrays, but am unsure how to ask it elegantly, so apologies in advance. Below is a screenshot of an object array we're dealing with. Is there a way to organize it so that the array index 0 is replaced by the value of column_name?

enter image description here

So for example, instead of the above, the array is structured as such:

hrService_Values:
  u_proposed_effective_date:
    display_value: "2019-12-22"
    label: "Proposed Effective Date"
    value: "2019-12-22 00:00:00"

Upvotes: 0

Views: 54

Answers (1)

Teslo.
Teslo.

Reputation: 501

I think what you want in this case is to NOT use an array, but a complex object. Only so you will end up having the structure you want, and that's because you have an array of objects.

hrService_Values: <- Object
  u_proposed_effective_date: <- Object
    display_value: "2019-12-22"
    label: "Proposed Effective Date"
    value: "2019-12-22 00:00:00"

If you want to do this on the frontend side, in plain vanilla JS, you'll have to iterate for each object of the array, get the property value you want and use it as a property name in the root object then copy the rest of the properties. Maybe something similar to this:

var myArray = new Array({
  'column_name': 'u_proposed_effective_date',
  'display_value': '2019-12-12',
  'label': 'Proposed Effective Date',
  'value': '2019-12-22 00:00:00'
}, {
  'something_else': 'blA BLA'
});

console.log(myArray);

var hrService_Values = {};
myArray.forEach(function(item, index) {
  if (item.column_name) {
    var newObj = { ...item };
    delete newObj.column_name;
    hrService_Values[item.column_name] = newObj;
  }
});

console.log(hrService_Values);

Upvotes: 1

Related Questions