将对象格式化为嵌套字段

时间:2019-07-14 17:43:09

标签: javascript object

我正在使用for循环遍历两个数组并生成一个对象。可以,但是我需要最终对象的格式略有不同。

首先,这是遍历数组并形成我的对象的代码:

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;
      }
    }
  }

这给了我一个看起来像这样的对象:

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

我需要适合我的模型的格式应为:

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

我可以在此处使用哪些操作来格式化所需的格式?

1 个答案:

答案 0 :(得分:1)

您可以使用通向所需属性的路径,将其拆分,然后将值分配给最新对象。

//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);