将对象组合在一对多关系中

时间:2017-11-14 16:16:58

标签: javascript object

我有一段输出多个对象数组的代码。如何将这些对象合并在一起,以便我可以获得具有一对多关系的组合对象?

Plunkr link

var newGender = { gender: "Male" };
var newFruit = [{ fruits: "Apple" }, { fruits: "Orange" }, { fruits: "Kiwi" } ];
var newName = "My name";

如何编写将这些数据组合在一起的函数,以便得到这样的数组?

[
    {
        gender: "Male",
        name: "My name",
        fruits: "Apple"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Orange"
    },
    {
        gender: "Male",
        name: "My name",
        fruits: "Kiwi"
    }
]

我选择的水果中的每个条目都应该是一个单独的对象。

1 个答案:

答案 0 :(得分:2)

由于水果是唯一可以选择多个值的项目,因此非常简单:



function combineSelections(name, gender, fruits) {
  if (!(name && gender && fruits)) {
    return [];
  }

  return fruits.map(function(fruit) {
    return {
      name: name,
      gender: gender.gender,
      fruit: fruit.fruits
    };
  });
}

var newName = 'Arun';
var newGender = {
  gender: 'male'
};
var newFruits = [
  { fruits: 'kiwi' },
  { fruits: 'dragonfruit' },
  { fruits: 'mango' }
];

console.log(combineSelections(newName, newGender, newFruits));