【问题标题】:How to push properties of array to another array?如何将数组的属性推送到另一个数组?
【发布时间】:2023-03-31 03:49:01
【问题描述】:

这是我的数组,dataCom

id: "5c9e3f0aa289e606b46a7fdf"
importPrices: 500
name: "Wings spring"
owner: "5c40442b6e4425163915e5b3"
priceBaseOnBOM: 0
productId: "LXCM"
salePrices: 0

我想像这样将一些属性传递给新数组(组件)

components.push({
          salePrices: dataCom.salePrices,
          productId:dataCom.productId,
          name: dataCom.name,
          amount: dataCom.amount,
          id: dataCom.id})

但这是不对的。我想要这样的组件

components
[
    id: "5c9e3f0aa289e606b46a7fdf",
    name: "Wings spring",
    productId: "LXCM"
    salePrices: 0
]

请帮忙,非常感谢

【问题讨论】:

  • 你想要的输出是一个数组,它包含键,否则不可能用对象数组或单个对象数组替换它

标签: javascript arrays object ecmascript-6


【解决方案1】:

试试这个,

var dataCom = {
  id: "5c9e3f0aa289e606b46a7fdf",
  importPrices: 500,
  name: "Wings spring",
  owner: "5c40442b6e4425163915e5b3",
  priceBaseOnBOM: 0,
  productId: "LXCM",
  salePrices: 0
};
var components = [];
var obj= {
  id: dataCom.id,
  name: dataCom.name,
  productId: dataCom.productId,
  salesPrices: dataCom.salePrices
};
for(var b=0; b<keys(obj).length;b++){
    components[keys(obj)[b]] = obj[keys(obj)[b]]
} 
console.log(components);

上面的代码会给你下面的答案

输出

components
[
  id: "5c9e3f0aa289e606b46a7fdf",
  name: "Wings spring",
  productId: "LXCM"
  salePrices: 0
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多