使用传播算子向对象添加属性

时间:2018-07-23 10:59:42

标签: javascript

我在代码中使用了扩展运算符将属性添加到对象,但是IE 9不支持。重要的部分是...currentItem

const data = [
  [{
    name: "item 3",
    value: 2
  }],
  [{
    name: "item 4",
    value: 4535
  }, {
    name: "item 5",
    value: 897
  }]
];

$(document).ready(() => {

  const newData = data.map(subArr =>
    subArr.map((currentItem, index) => ({ ...currentItem,
      position: index - (subArr.length - 1) * 0.5
    }))
  );

  console.log(newData);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我试图将其转换为不使用传播运算符的代码

const data = [
  [{
    name: "item 3",
    value: 2
  }],
  [{
    name: "item 4",
    value: 4535
  }, {
    name: "item 5",
    value: 897
  }]
];

$(document).ready(() => {

  const newData = data.map(subArr =>
    subArr.map((currentItem, index) => ({
      name: currentItem.name,
      value: currentItem.value,
      position: index - (subArr.length - 1) * 0.5
    }))
  );

  console.log(newData);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

,这确实很好。但是问题是,我必须写下当前对象的所有属性。假设有五个以上的属性。因此,我尝试通过执行以下代码将新属性添加到当前对象中

const data = [
  [{
    name: "item 3",
    value: 2
  }],
  [{
    name: "item 4",
    value: 4535
  }, {
    name: "item 5",
    value: 897
  }]
];

$(document).ready(() => {

  const newData = data.map(subArr =>
    subArr.map((currentItem, index) => (
      currentItem.position = index - (subArr.length - 1) * 0.5
      /* currentItem["position"] = index - (subArr.length - 1) * 0.5 */
    ))
  );

  console.log(newData);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

但是现在该对象被转换为我要添加的单个属性。所以这是行不通的。如何在arr.map循环中将新属性添加到对象?

重要:使用Jquery只是一个示例。请提供不使用Jquery的解决方案。

3 个答案:

答案 0 :(得分:1)

可以用Object.assign替换扩展运算符,但是ie不支持。

您可以像在this answer中那样填充它:

 if (typeof Object.assign != 'function') {
  Object.assign = function(target, varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
}

const data = [
  [{
    name: "item 3",
    value: 2
  }],
  [{
    name: "item 4",
    value: 4535
  }, {
    name: "item 5",
    value: 897
  }]
];

document.addEventListener("DOMContentLoaded", () => {

  const newData = data.map(subArr =>
    subArr.map((currentItem, index) => (Object.assign(currentItem, {
      position: index - (subArr.length - 1) * 0.5
    })))
  );

  console.log(newData);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

您可以使用Object.assign()https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Object/assign)而不是传播运算符:

Object.assign({}, currentItem, position)

答案 2 :(得分:0)

如果我理解的正确,则可以使用Object.defineProperty,看起来它在IE enter link description here中受支持

  const data = [
  [{
    name: "item 3",
    value: 2
  }],
  [{
    name: "item 4",
    value: 4535
  }, {
    name: "item 5",
    value: 897
  }]
];

let newData = data.map(arr => {
    let obj = {};
    arr.map((item, index) => {
        Object.defineProperty(obj, 'position', {
            value: index - (arr.length - 1) * 0.5,
            configurable: true
        });
    });
    return obj;
});

console.log(newData);