Javascript-修改数组值

时间:2018-08-28 14:10:39

标签: javascript jquery arrays

我有一个像这样的javascript数组。

0: {color: "green", shape: "round"}
1: {color: "red", shape: "square"}
3: {color: "blue", shape: "flat"}

我正试图像这样改变形状的值。

myarray[1] = {shape: "oblong"};

但这也要删除颜色值,我该如何做并保留其他值?

4 个答案:

答案 0 :(得分:9)

这是因为要设置数组值,而不是基础对象的属性shape

 myarray[1].shape =  "oblong";

答案 1 :(得分:1)

修改对象的另一种方法是使用Object.assign函数,因此看起来像这样:

myarray[1] = Object.assign(myarray[1], {shape: "oblong"});

答案 2 :(得分:0)

$arr = '[
    {
        "Contact name(s)": "Person 1, Person 2",
        "Contact title(s)": "Head Comacho, Other Guy",
        "Contact email(s)": "email1@email.net, email@email.com",
        "Contact phone": "123-456-7890, 789-456-1230"
    },
    {   
        "Contact name(s)": "Some Dude",
        "Contact title(s)": "Cool Title",
        "Contact email(s)": "things@email.com",
        "Contact phone": "555-555-5555"
    },
    {
        "Contact name(s)": "",
        "Contact title(s)": "",
        "Contact email(s)": "",
        "Contact phone": ""
    }
]';

$arr = json_decode($arr, true);

foreach ($arr as $row) {

    list($m_name, $m_title, $m_email, $m_phone) =
    [explode(',', $row["Contact name(s)"]),explode(',', $row["Contact title(s)"]),
     explode(',', $row["Contact email(s)"]),explode(',', $row["Contact phone"])];

    foreach (array_keys($m_name) as $per)
        $result[] = ['name' => $m_name[$per],'title' => $m_title[$per],
                     'email' => $m_email[$per],'phone' => $m_phone[$per]];
}

var_dump($result);

答案 3 :(得分:0)

您的数组中包含多个对象。每个元素都是一个包含2个属性(颜色和形状)的对象。

如果您这样做

myarray[1] = {shape: "oblong"};

您正在将新对象分配给myarray的索引1,因此剩下的就是只有一个属性(形状)的新对象。

如果您改为这样做

myarray[1].shape = "oblong";

myarray [1]中的对象将是:

color: "red", shape: "oblong"}