javascript - 如何在javascript中操作对象数组
问题描述
我正在尝试操作下面给出的对象,我需要根据qty
和warehouse
属性将对象划分为多个对象。
var response = [
{
"name": "test1",
"qty": 3, //divid obj to 3 times as qty haing 3
"warehouse": {
"india": 2,
"Usa": 1
}
},
{
"name": "test2",
"qty": 1,
"warehouse": {
"india": 1
}
},
{
"name": "test3",
"qty": 1,
"warehouse": {
}
}
]
// here i am trying to manipulate to get the result
const finalResponse = response.map(item=>{
if((item.qty>=1) && (Object.keys(item.warehouse).length >= 1)){
const warehouses = item.warehouse;
const arr=[]
Object.keys(warehouses).forEach((key)=>{
if(warehouses[key]>=1){
arr.push(...Array(warehouses[key]).fill({...item,[key]:1}))
}
})
return arr;
}
})
在这里,我试图在下面获得输出,但我无法正确解决
finalResponse =[ {
"name": "test1",
"qty": 1,
"india": 1
},
{
"name": "test1",
"qty": 1,
"india": 1
},
{
"name": "test1",
"qty": 1,
"Usa": 1
},
{
"name": "test2",
"qty": 1,
"india": 1
},,
{
"name": "test3",
"qty": 1,
"warehouse": {
}
} ];
解决方案
const result = []
response.forEach((item) => {
const { warehouse, qty: _useless, ...rest } = item;
Object.entries(warehouse).forEach(([key, value]) => {
const resultItem = {
...rest,
qty: 1, // this is always 1 right?
[key]: 1, // and this is also 1 always
}
result.push(...Array(value).fill(resultItem))
})
});
// result
[
{ name: 'test1', qty: 1, india: 1 },
{ name: 'test1', qty: 1, india: 1 },
{ name: 'test1', qty: 1, Usa: 1 },
{ name: 'test2', qty: 1, india: 1 }
]
推荐阅读
- php - 在选择查询中使用 mysql_num_rows 和选择
- talend - 如何使用 Talend Integration 比较行?
- javascript - 在 Internet Explorer 中,无法跳转到另一个页面
- javascript - 从嵌套回调函数中返回方法
- windows - SonarQube 6.4 Wrapper 在 Windows 中停止
- eclipse-scout - 在特定时间显示表格
- php - Woocommerce 不会取消暂停状态的订单
- r - 模型矩阵不是数字矩阵吗?
- hibernate - 使用休眠获取在数据库中创建的 Id 的值
- wso2 - Siddhi 应用程序在运行工作程序时无法部署 siddhi 应用程序