首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中直接分配对象

在javascript中直接分配对象
EN

Stack Overflow用户
提问于 2018-03-20 10:11:53
回答 2查看 54关注 0票数 0

如何在不更改其他属性的情况下替换对象属性,如果分配的对象数量不均衡,则复制其他属性?

我想这个问题可能没有任何意义。这个例子可以解释一切。让我说:

代码语言:javascript
复制
var oldData = {
  fruits: fruits,
  veggies: [{
      sweet: false,
      colour: red,
      data: [1, 2, 3]
    }]
};

var newData = {
  veggies: [{
    sweet: true,
    data: [99, 100, 101]
  },
  {
    sweet: false,
    data: [888, 777, 665],
  }]
};

var standardColor = "blue";

目标是:

  • 用新数据取代旧蔬菜数据
  • 用新的甜值取代旧的蔬菜甜值
  • 保留旧的蔬菜颜色值,除非在新的数据中有一个新的,因此替换它。
  • 如果下面的新蔬菜对象没有颜色,请使用standardColor -“蓝色”
  • 保持水果不动

问题:

  • newData蔬菜可以有比oldData更多的对象,因此我需要以某种方式迭代它们吗?

我的拙劣尝试:

代码语言:javascript
复制
function replaceVeggies (newData) {
  oldData.veggies = newData.veggies
};
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-20 12:41:01

这应该对你有用。

我添加了一些额外的数据来测试一些需求。

代码语言:javascript
复制
var oldData = {
  fruits: "fruits",
  veggies: [{
      sweet: false,
      colour: "red",
      data: [1, 2, 3]
    },
    {
      sweet: true,
      // colour: "red",
      data: [1, 2, 3]
    }
  ]
};

var newData = {
  veggies: [{
      sweet: true,
      data: [99, 100, 101]
    },
    {
      sweet: false,
      data: [888, 777, 665]
    },
    {
      sweet: false,
      data: [444, 558, 333]
    }
  ]
};

var standardColor = "blue";

// Iterate through the newData object
for (var i = 0; i < newData.veggies.length; i++) {

  var newVeggie = newData.veggies[i];

  // Check if the index value exists on the old array
  if (oldData.veggies[i] !== null && (typeof oldData.veggies[i] !== "undefined")) {

    // Always replace data
    oldData.veggies[i].data = newVeggie.data;

    // Always replace sweet value
    oldData.veggies[i].sweet = newVeggie.sweet;

    // Replace colour if exists in new data
    if (newVeggie.colour !== undefined) {

      oldData.veggies[i].colour = newVeggie.colour;

    } else {

      // If old data didn't have colour value set default
      if (oldData.veggies[i].colour == undefined) {
        oldData.veggies[i].colour = standardColor;
      }

    }

  } else {

    // Check if the colour is null
    if (newData.veggies[i].colour == undefined) {

      newData.veggies[i].colour = standardColor;

    }

    // Assign the new veggie directly
    oldData.veggies[i] = newVeggie;
  }

  console.log("Veggie " + i);

  // Iterate over the properties
  Object.keys(oldData.veggies[i]).forEach(function(key) {

    console.log("  " + key + ": " + oldData.veggies[i][key]);

  });
}

票数 1
EN

Stack Overflow用户

发布于 2018-03-20 10:24:51

JS内置的Object.assign为您处理这个问题:

代码语言:javascript
复制
const x = {
  y: 10,
  z: 20
}

console.log(JSON.stringify(x))

console.log(JSON.stringify(Object.assign(x, { y : 30, a: 45 })))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49381415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档