【问题标题】:How to fetch particular data from array of objects and store in new array in js (vue js)如何从对象数组中获取特定数据并存储在js(vue js)中的新数组中
【发布时间】:2021-08-15 14:24:29
【问题描述】:

我有这个对象数组

let detail : [ 
       0: {
            Code: "Code 1"
            Price: "0.00"   
          },           

       1: {
            Code: "Code 2"
            Price: "9.00"   
          }
]

我想将价格存储在一个数组中(例如:结果),以便我可以将它与对象的另一个现有数组合并(例如:alldetail)

result = [
    0: {
          Price:"0.00"
       },
    1: {
          Price:"9.00"
       },   
]

【问题讨论】:

  • 上面的sn-p不是有效的JS代码。假设 detail 是一个对象数组,您可以通过 let result = detail.map(item => ({Price: item.Price}))
  • 是的,你是对的,但我之前没有看过 map 函数,现在它与 map 函数一起工作。谢谢@EugeneKarataev

标签: javascript arrays vue.js object


【解决方案1】:

使用map() 方法创建一个新数组,其中填充了在调用数组中的每个元素上执行的所提供函数的结果。

因此,在您的情况下,您将返回一个具有键 Price 的对象,其值将是当前对象,其值为 Price 属性。

let detail = [ 
        {
            Code: "Code 1",
            Price: "0.00"   
          },           

       {
            Code: "Code 2",
            Price: "9.00"   
          }
];

let result = detail.map(current => {return {Price: current.Price}});

console.log(result);

【讨论】:

  • 我还有一个问题,如果 Price 是一个对象数组怎么办。如何访问该键值? @RanTurner
【解决方案2】:

使用map 创建一个新的对象数组。

const detail = [ 
  { Code: "Code 1", Price: "0.00" },           
  { Code: "Code 2", Price: "9.00" }
];

const result = detail.map(({ Price }) => ({ Price }));

console.log(result);

其他文档

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2018-09-16
    相关资源
    最近更新 更多