将嵌套的对象数组与父对象合并

时间:2018-09-30 12:03:51

标签: javascript underscore.js lodash

var data = {
      food:"chicken", 
      list:[
             { name: "wings", qty: "25", price: "4,900", payment:"Cash" },
             { name: "lap", qty: "50", price: "9,900", payment: "Credit" }
           ]
      }

我上面是通过php laravel模型关系从ajax接收到此数据的,我想使用javascript或任何库来转换以下格式的数据。

下面的数据是所需的。

var data = [
    { food:"chicken", name: "wings", qty:"25", price:"4,900", payment:"Cash" },
    { food:"chicken", name: "lap", qty:"50", price:"9,900", payment:"Credit" }        
]   

3 个答案:

答案 0 :(得分:0)

getList功能代码可以为您提供帮助:

let getList = function(data, arrayKey, arrayName) {
 data[arrayKey].forEach(function(element) {
   element[arrayName] = data[arrayName]
 }); return data[arrayKey];
};

在这里您可以看到上面功能的运行示例:

const data = {
  food: "chicken",
  list: [{
      name: "wings",
      qty: "25",
      price: "4,900",
      payment: "Cash"
    },
    {
      name: "lap",
      qty: "50",
      price: "9,900",
      payment: "Credit"
    }
  ]
};

let getList = function(data, arrayKey, arrayName) {
 data[arrayKey].forEach(function(element) {
   element[arrayName] = data[arrayName]
 }); return data[arrayKey];
};

let result = getList(data, "list", "food");
console.log(result);

答案 1 :(得分:0)

您可以轻松地解决此问题,方法是遍历每个项目并将食物对象添加到该对象,如下所示:

data.list.forEach((oneItem) => {
     oneItem.food = data.food;
});
data = data.list; //keep the array of list objects only

答案 2 :(得分:0)

不使用lodash且仅使用ES6的一种方法是通过mapObject.assign

var data = { food: "chicken", list: [{ name: "wings", qty: "25", price: "4,900", payment: "Cash" }, { name: "lap", qty: "50", price: "9,900", payment: "Credit" } ] }

var result = data.list.map(x => Object.assign(x, {food: data.food}))
console.log(result)

使用lodash/fp,它看起来像:

var result = _.flow(_.map(_.extend({ food: data.food })))(data.list)

lodash中:

var result = _.map(data.list, x => _.extend(x, {food: data.food}))