Rey
Rey

Reputation: 1433

Format Object Into Nested Fields

I am using a for loop to iterate over two arrays and generate an object. That's working, but I need the final object in a slightly different format.

First off, here's the code that iterates over the arrays and forms my object:

differences:
   [ { kind: 'N', path: ['id_number'], rhs: '1' },
     { kind: 'N', path: ['person_firstname'], rhs: 'x1' },
     { kind: 'N', path: ['person_lastname'], rhs: 'x2' } ]

mappings: [ { lhs: 'name.first', rhs: 'person_firstname' },
  { lhs: 'name.last', rhs: 'person_lastname' },
  { lhs: 'name.middle', rhs: 'person_middlename' } ]

  let outResult = {};

  for (let diff of differences) {
    for (let mapping of mappings) {
      if (diff.path[0] === mapping.rhs) {
        p = mapping.lhs;
        v = diff.rhs;
        outResult[p] = v;
      }
    }
  }

What this gives me is an object that looks like this:

{ name.first: 'x1', name.last: 'x2' }

The format I need to fit my model should be this:

name: {
    first: "x1",
    last: "x2"
  }
};

What operation(s) can I use here to format this in the way I need?

Upvotes: 1

Views: 32

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

You could take the path to the wanted property, split it and assign the value to the latest object.

//instead of 
outResult[p] = v;

// take
setValue(outResult, p, v);

function setValue(object, path, value) {
    var keys = path.split('.'),
        last = keys.pop();
        
    keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}


var differences = [{ kind: 'N', path: ['person_firstname'], rhs: '1' }, { kind: 'N', path: ['person_lastnam'], rhs: 'testing1' }, { kind: 'N', path: ['id_number'], rhs: 'tseting2' }],
    mappings = [{ lhs: 'name.first', rhs: 'person_firstname' }, { lhs: 'name.last', rhs: 'person_lastname' }, { lhs: 'name.middle', rhs: 'patient_middlename' }],
    outResult = {};

for (let diff of differences) {
    for (let mapping of mappings) {
        if (diff.path[0] === mapping.rhs) {
            setValue(outResult, mapping.lhs, diff.rhs);
        }
    }
}

console.log(outResult);

Upvotes: 1

Related Questions