从Object.keys和forEach方法javascript获取新对象

时间:2018-02-23 22:35:49

标签: javascript express foreach key

我正在尝试使用来自结构不良的现有对象数组(数组?)的新键和道具创建一个新对象(newobj)。

[{"product":["1009", "name", "price", "image", "description"]},
 {"product":["1004", "name2", "price2", "image2", "description2"]}]

我得到了我想要的结果但是newobj不会在forEach方法的范围之外更新(超过1个结果)。我的问题是我没有得到什么?这种类型obj是forEach不正确的方法吗?

    var newobj = {};

    Object.keys(oldobj).forEach(function(prop) {
      newobj["id"] = Number(oldobj[prop]["product"][0]),
      newobj["name"] = oldobj[prop]["product"][1],
      newobj["price"] = Number(oldobj[prop]["product"][3]),
      newobj["image"] = "url" + oldobj[prop]["product"][0] + ".jpg",
      newobj["description"] = oldobj[prop]["product"][2];
      // this works
      // console.log(JSON.stringify(newobj));
    });
   // this only updated with one 
    app.locals.newobj = newobj;

我也尝试过映射(带下划线)但是我有相同的结果,我无法访问外部范围。

_.each(mappedobj, function(prop) {
            _.each(prop["product"][0], function(vals){
                     newobj["id"] = Number(prop["product"][0]);
                     console.log(JSON.stringify(newobj));
            });
        });

3 个答案:

答案 0 :(得分:1)

如果您想要旧对象的所有值,则需要使newobj成为一个对象数组。您可以使用.map()进行此转换。

对象和数组解构是避免所有这些硬编码索引的便捷方法。通过正确命名参数变量,您可以使用object literal简写来更轻松地创建结果对象。



var oldobj = [{
    "product": ["1009", "name", "price", "image", "description"]
  },
  {
    "product": ["1004", "name2", "price2", "image2", "description2"]
  }
];
var newobj = oldobj.map(({product: [id, name, price, url, description]}) =>
    ({id: Number(id), name, price: Number(price), url: `url${url}.jpg`, description})
);
console.log(newobj);




答案 1 :(得分:0)

试试这个

let newObject = _.map(oldObject, (item) => {
    return {
       id: item.product[0],
       name: item.product[1],
       price: item.product[2],
       image: item.product[3],
       description: item.product[4]
    };
});

答案 2 :(得分:0)

如果要将结构不良的对象数组转换为结构良好的对象数组,可以使用VanillaJS的Array.prototype.map



const data = [
  {"product": ["1009", "name", "120", "image", "description"]},
  {"product": ["1004", "name2", "250", "image2", "description2"]},
  {"product": ["1012", "name3", "85", "image3", "description3"]}
];

const products = data.map(({ product }) => {
  const [id, name, price, image, description] = product;

  return {
    id: Number(id),
    name,
    price: Number(price),
    image: `url${image}.jpg`,
    description
  };
});

console.log(products);