更新JavaScript中对象的多个值

时间:2018-08-16 00:01:11

标签: javascript

提供对象

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.kdgeiger.ezbudget.Overview">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="48sp"
            android:background="@color/green"
            android:gravity="center"
            android:includeFontPadding="false"
            android:textColor="@color/white"
            android:textSize="28sp"
            android:text="@string/overview"/>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:id="@+id/navList"
            android:layout_width="200dp"
            android:layout_height="match_parent"
            android:layout_gravity="left|start"
            android:background="@color/white"
            android:divider="@null"/>

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>

如果要更改多个值,请执行以下操作:

var myObject = {
    label: 'foo',
    name: 'bar',
    id: 12
},

在更新大数据集时,这会使代码变得很块状。有没有一种方法可以更简洁地做到这一点?

赞:

myObject.label = "bar";
myObject.name = "foo";

2 个答案:

答案 0 :(得分:19)

Object.assign很适合:

var myObject = {
    label: 'foo',
    name: 'bar',
    id: 12
}
Object.assign(myObject, {label: 'Test', name: 'Barbar'})
console.log(myObject)

答案 1 :(得分:7)

除了Object.assign,您还可以使用对象散布运算符:

var myObject = {
    label: 'foo',
    name: 'bar',
    id: 12
};

myObject = {...myObject, label: 'baz', name: 'qux'};
console.log(myObject);

// Or, if your update is contained in its own object:

var myUpdate = {
    label: 'something',
    name: 'else'
}

myObject = {...myObject, ...myUpdate}
console.log(myObject)