【问题标题】:How to iterate a single object into a new array of multiple objects within a defined format如何将单个对象迭代到定义格式内的多个对象的新数组中
【发布时间】:2020-05-15 11:06:10
【问题描述】:

我有以下具有多个属性的对象

let features: {
  durable: 5,
  weight: 4
}

我需要将其转换为服务器接受的某种格式,如下例所示。上述features 值放入value 属性和features 属性名称(“耐用”等)放入category.name

"score": [
  {
    "value": 5,
    "category": {
      "name": "durable"
    }
  },
  {
    "value": 4,
    "category": {
      "name": "weight"
    }
  }
]

在 POST 服务中,我将数据输入到属性中,然后将其发送到服务器(简化示例)。新的对象数组应在下面的ratings 属性中声明

const scoreData= {
  title: something,
  ratings: score
};

return this.http.post(this.API_URL, scoreData);

编辑:所选解决方案确实有效!但可能过于复杂?为了比较,将features 对象的键和值属性迭代新数组的方法是什么,例如:

const scoreData = {
            title: "something",
            ratings: [
                {
                    "value": features.value, // Iterating through values here
                    "category": {
                        "name": features.key // ... and here
                    }
                }
            ]
        };

【问题讨论】:

    标签: javascript arrays angular javascript-objects


    【解决方案1】:

    您想将该特定对象转换为上述指定格式吗?如果是这样,您可以这样做:

    var k={features: { durable: 5, weight: 4}};
    
    var score = Object.entries(Object.values(k)[0]).map(([k,v])=> ({ value : v, category: { name : k } }));
    
    console.log(score);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多