从其他对象填充对象中的字段

时间:2019-03-11 13:40:07

标签: javascript ecmascript-6

在Javascript(ES6)中,有两个带有数据的对象。

const template = {
    a: '',
    b: '',
    x: ''
}

这是我将收到的数据对象

const data = {
    a: 'test',
    b: 'test',
    c: 'test'
}

如何将数据从接收到的对象映射到模板对象,而不允许模板对象中不存在值。

所以结果应该是这样。

const result = {
    a: 'test',
    b: 'test',
    x: ''
}

8 个答案:

答案 0 :(得分:4)

您可以使用for...in循环:

const template = {
  a: '',
  b: ''
}

const data = {
  a: 'test',
  b: 'test',
  c: 'test'
}

const result = {};

for (let k in template) {
  result[k] = data[k];
}

console.log(result)

答案 1 :(得分:3)

类似这样的东西:

 let result = {};
 const template = {
      a: '',
      b: ''
 }
 const data = {
     a: 'test',
     b: 'test',
     c: 'test'
 }

 for (let prop in data) {
    if(prop in template) result[prop] = data[prop];
 }

 console.log(result);

答案 2 :(得分:3)

您可以从template获取具有相同键的data对象和属性。

const
    template = { a: '', b: '', x: '' },
    data = { a: 'test', b: 'test', c: 'test' },
    result = Object.assign(
        {},
        template,
        ...Object.keys(template).map(k => k in data && { [k]: data[k] })
    );
    
console.log(result);

答案 3 :(得分:2)

只是为了好玩,您可以使用一些代理魔法:)

const template = {
  a: '',
  b: ''
}

const data = {
  a: 'test',
  b: 'test',
  c: 'test'
}

const result = { ...new Proxy(data, {
    ownKeys: () => Object.keys(template)
  })
}

console.log(result)

答案 4 :(得分:0)

您可以使用Array.reduce来查看对象,并仅更改您感兴趣的键。此方法还将处理您要从data复制的键不在此处的情况。另外,我们已经创建了一个新对象,我们不会更改现有对象。


无突变(新对象)

const template = {
  a: '',
  b: '',
};

const data = {
  a: 'test',
  b: 'test',
  c: 'test',
};

const ret = Object.keys(template).reduce((tmp, x) => {
  tmp[x] = data[x] !== void 0 ? data[x] : tmp[x];

  return tmp;
}, {
  ...template,
});

console.log(ret);


突变对象(使用旧对象)

const template = {
  a: '',
  b: '',
};

const data = {
  a: 'test',
  b: 'test',
  c: 'test',
};

Object.keys(template).forEach((x) => {
  template[x] = data[x] !== void 0 ? data[x] : template[x];
});

console.log(template);

答案 5 :(得分:0)

const template = {
  a: '',
  b: ''
}

const data = {
  a: 'test',
  b: 'test',
  c: 'test'
}

function setData(inputTemplate, inputData) {
    outputObject = {}
    for (var key in inputTemplate) {
        if (inputData[key]) {
          outputObject[key] = inputData[key];
        }
    }
    return outputObject
}

console.log(setData(template, data))

答案 6 :(得分:0)

您可以简单地循环使用模板的键,并使用相同的键为数据对象设置值。

const data = {
    a: 'test',
    b: 'test',
    c: 'test'
}

const template = {
    a: '',
    b: ''
}

Object.keys(template).forEach((key) => template[key] = data[key])

console.log(template)

答案 7 :(得分:0)

您还可以使用 reduce

示例:

const template = {
  a: '',
  b: ''
}

const data = {
  a: 'test',
  b: 'test',
  c: 'test'
}

const res = Object.keys(template).reduce((all, acc) => {
  all[acc] = data[acc]
  return all
}, {})

console.log(res)

相关问题