首页 > 解决方案 > 如何在不通过循环的情况下将一个对象与 JavaScript 中的其他对象内部值合并?

问题描述

如果我的state对象是这样的,

this.state={
  input:{
    employee_count_range: {
        value: props.employee_count_range || '',
        errMsg: null
    },
    phone: {
        value: '',
        errMsg: null
    },
    city: {
        value: '',
        errMsg: null
    }
  }
}

user对象是这样的,

let user = {
   employee_count_range: '',
   phone: '',
   city: ''
}

有没有办法在不通过循环的情况下使用 ES6 做到这一点?

Object.keys(this.state.inputs)
     .map(field => user[field] = this.state.input[field].value);

我想将state每个内部的对象分配valueuser对象值

标签: javascriptreactjsecmascript-6

解决方案


在您对我的问题“动态发现 this.state.inputs 中的属性名称是否重要,或者按字面意思列出它们是否可以?”的回答中 你说过

可以按字面意思列出它们。我知道我可以用循环来做到这一点。我只想知道有没有可能。

当然,根本不需要循环,直接赋值是简单直接的方法:

user.employee_count_range = this.state.inputs.employee_count_range.value;
user.phone = this.state.inputs.phone.value;
user.city = this.state.inputs.city.value;

现场示例(使用state而不是this.state):

const state = {
  inputs: {
    employee_count_range: {
      value: 42
    },
    phone: {
      value: "123 456 7890"
    },
    city: {
      value: "London"
    }
  }
};
const user = {};

user.employee_count_range = state.inputs.employee_count_range.value;
user.phone = state.inputs.phone.value;
user.city = state.inputs.city.value;

console.log(user);

你也可以使用解构赋值来做到这一点,但它不会给你带来太多东西,而且阅读起来可能会很棘手:

({
  employee_count_range: {value: user.employee_count_range},
  phone: {value: user.phone},
  city: {value: user.city}
} = this.state.inputs);

现场示例(使用state而不是this.state):

const state = {
  inputs: {
    employee_count_range: {
      value: 42
    },
    phone: {
      value: "123 456 7890"
    },
    city: {
      value: "London"
    }
  }
};
const user = {};

({
  employee_count_range: {value: user.employee_count_range},
  phone: {value: user.phone},
  city: {value: user.city}
} = state.inputs);

console.log(user);


以下所有内容都假设您要动态查找属性名称,但事实证明并非如此。

如果你的意思是你想复制这个:

Object.keys(this.state.inputs)
     .map(field => user[field] = this.state.inputs[field].value);

...根本没有任何形式的循环结构,那么不,没有办法做到这一点。你需要某种循环。


map但是,这不是正确的选择,因为您没有使用它的返回值。forEachfor-of循环将是更合适的选择:

Object.keys(this.state.inputs)
    .forEach(field => user[field] = this.state.inputs[field].value);

或者

for (const field of Object.keys(this.state.inputs)) {
    user[field] = this.state.inputs[field].value;
}

this.state.iputs[field].value您可以使用Object.entries而不是避免第二次查找( ) Object.keys(但它涉及一堆临时数组,所以...权衡):

for (const [field, value] of Object.entries(this.state.inputs)) {
    user[field] = value;
}

或与forEach

Object.entries(this.state.inputs).forEach(([field, value]) => {
    user[field] = value;
});

推荐阅读