javascript-合并,合并,转换2个不同的对象数组

时间:2018-10-08 11:04:01

标签: javascript arrays javascript-objects

我不知道如何转换和组合2个对象数组。

我有这2个对象数组:

const selectedCourse = [
    {
      "courseType": [5],
      "id": 26,
      "title": "Apple Tart with Apricot Glaze",
  },
  {
    "courseType": [3],
    "id": 16,
    "title": "Classic Caesar Salad",
},
{
  "courseType": [1,2],
  "id": 10,
  "title": "Lobster Bisque",
},
{
  "courseType": [3],
  "id": 16,
  "title": "Classic Caesar Salad",
},
]

const courseTypes = [
{name: "Hors d'oeuvres", id: 0},
 {name: "Soup", id: 1},
 {name: "Fish", id: 2},
 {name: "Salad", id: 3},
 {name: "Main course", id: 4},
 {name: "Dessert", id: 5}
]

第一个JSON中的 courseType 属性是一个数字数组,与第二个JSON中的 courseTypes 索引和属性 id 相对应。< / p>

此案例的结果应为:

const result = [
  {
    courseType: 1,
    courseName: "Soup",
    courses: [
      {
        "courseType": [1,2],
        "id": 10,
        "title": "Lobster Bisque",
      }      
    ]
  },
  {
    courseType: 3,
    courseName: "Salad",
    courses: [
      {
        "courseType": [1,2],
        "id": 10,
        "title": "Lobster Bisque",
      }      
    ]
  },
  {
    courseType: 3,
    courseName: "Fish",
    courses: [
      {
        "courseType": [3],
        "id": 16,
        "title": "Classic Caesar Salad",
      },
      {
        "courseType": [3],
        "id": 16,
      },      
    ]
  },
  {
    courseType: 5,
    courseName: "Main course",
    courses: [
      {
        "courseType": [5],
        "id": 26,
        "title": "Apple Tart with Apricot Glaze",
      }
    ]
  }
]

预期结果必须通过 courseType 属性进行过滤,从而将2个数组组合在一起。

3 个答案:

答案 0 :(得分:1)

假设您希望所有带有 <profile> <id>at1Test</id> <properties> <server.port>*****</server.port> <server.address>****</server.address> <server.remote>true</server.remote> </properties> </profile> 的项目,可以选择selectedCourse并收集所有课程,然后从找到的值中扩充一个新数组。

此解决方案还包括 Fish

Map
const
    selectedCourse = [{ courseType: [5], id: 26, title: "Apple Tart with Apricot Glaze" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }, { courseType: [1, 2], id: 10, title: "Lobster Bisque" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }],
    courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }],
    map = selectedCourse.reduce((m, o) => o.courseType.reduce((n, id) => n.set(id, [...(n.get(id) || []), o]), m), new Map),
    result = courseTypes.reduce(
        (r, { name: courseName, id: courseType }) => (map.get(courseType) || []).reduce((s, courses) => s.concat({ courseType, courseName, courses }), r),
        []
    );
   
console.log(result);

答案 1 :(得分:0)

您可以像这样使用mapfilter

const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]

const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];

const result = courseTypes.map(courseType => ({
    courseType: courseType.id, 
    courseName: courseType.name,
    courses: selectedCourse.filter(course => course.courseType.includes(courseType.id))
})).filter(extended => extended.courses.length);

console.log(JSON.stringify(result, null, 2));

说明:

courseTypes.map遍历第二个输入数组,并为selectedCourse中的每种类型找到与该特定类型匹配的课程。

它使用.filter来收集那些匹配项。 filter回调使用includes来确定是否匹配-它返回一个布尔值,即过滤器回调期望的返回值。

然后,将此过滤后的数组添加到对象常量中,该对象常量还定义了其他两个属性courseTypecourseName。该新对象就是课程类型所映射的对象。 courseTypes.map返回这些对象的数组。

最后,该结果可能包含具有空courses数组的条目。再次调用.filter会将其过滤掉。如果该length数组的courses不为零,则保留该对象,否则将其踢出结果。

对于较旧的浏览器

以下是与旧版浏览器兼容的代码(没有箭头功能,没有includes,这是ES2015中引入的):

const selectedCourse = [ { "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, { "courseType": [1,2], "id": 10, "title": "Lobster Bisque", }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad", }, ]

const courseTypes = [ {name: "Hors d'oeuvres", id: 0}, {name: "Soup", id: 1}, {name: "Fish", id: 2}, {name: "Salad", id: 3}, {name: "Main course", id: 4}, {name: "Dessert", id: 5} ];

const result = courseTypes.map(function (courseType) {
    return {
        courseType: courseType.id, 
        courseName: courseType.name,
        courses: selectedCourse.filter(function (course) {
            return course.courseType.indexOf(courseType.id) > -1;
        })
    };
}).filter(function (extended) {
    return extended.courses.length;
});

console.log(JSON.stringify(result, null, 2));

答案 2 :(得分:0)

虽然“ trincot”代码在chrome和Mozila上可以正常使用,但在IE edge和IE 10及以下版本中将无法使用,您需要将其转换为纯JavaScript。以下是适用于所有浏览器的代码。

if (!Array.prototype.includes) {
   Object.defineProperty(Array.prototype, 'includes', {
   value: function(searchElement, fromIndex) {

  if (this == null) {
    throw new TypeError('"this" is null or not defined');
  }

  // 1. Let O be ? ToObject(this value).
  var o = Object(this);

  // 2. Let len be ? ToLength(? Get(O, "length")).
  var len = o.length >>> 0;

  // 3. If len is 0, return false.
  if (len === 0) {
    return false;
  }

  // 4. Let n be ? ToInteger(fromIndex).
  //    (If fromIndex is undefined, this step produces the value 0.)
  var n = fromIndex | 0;

  // 5. If n ≥ 0, then
  //  a. Let k be n.
  // 6. Else n < 0,
  //  a. Let k be len + n.
  //  b. If k < 0, let k be 0.
  var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

  function sameValueZero(x, y) {
    return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
  }

  // 7. Repeat, while k < len
  while (k < len) {
    // a. Let elementK be the result of ? Get(O, ! ToString(k)).
    // b. If SameValueZero(searchElement, elementK) is true, return true.
    if (sameValueZero(o[k], searchElement)) {
      return true;
    }
    // c. Increase k by 1. 
    k++;
  }

  // 8. Return false
  return false;
    }
  });
}
var selectedCourse = [{ "courseType": [5], "id": 26, "title": "Apple Tart with Apricot Glaze" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }, { "courseType": [1, 2], "id": 10, "title": "Lobster Bisque" }, { "courseType": [3], "id": 16, "title": "Classic Caesar Salad" }];
var courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }];
var result = courseTypes.map(function (courseType) {
return {
    courseType: courseType.id,
    courseName: courseType.name,
    courses: selectedCourse.filter(function (course) {
        return course.courseType.includes(courseType.id);
    })
  };
}).filter(function (extended) {
   return extended.courses.length;
});

 console.log(JSON.stringify(result, null, 2));