javascript - 如何唯一合并两个 JSON 文件?

标签 javascript arrays json node.js merge

我想合并两个包含电影信息的 JSON 文件。这些文件有一些共同点。我想写第三个文件,其中包含所有电影,但不重复。

这是我目前所拥有的:

const fs = require('fs');
const path = require('path');

const readMovies1 = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(path.join(__dirname,'../models/movies.json'), 'utf8', (err, data1) => {
      if(err) reject(err);
      let data = JSON.parse(data1);
      resolve(data);
    });
  });
};

const readMovies2 = (data1) => {
  return new Promise((resolve, reject) =>{
    fs.readFile(path.join(__dirname,'../models/movies2.json'), 'utf8', (err, data) => {
      if(err) reject(err);
      data = JSON.parse(data);
      resolve([data1,data]);
    });
  });
};

const merging = (data1, data2) => {
   var args = arguments;
   var hash = {};
   var arr = [];
   for (var i = 0; i < args.length; i++) {
      for (var j = 0; j < args[i].length; j++) {
        if (hash[args[i][j]] !== true) {
          arr[arr.length] = args[i][j];
          hash[args[i][j]] = true;
        }
      }
    }
return arr;

};
readMovies1()
  .then(readMovies2)
    .catch((err) => console.error(err))
  .then((data) => console.log(merging(data[0],data[1])))
    .catch((err) => console.error(err));

但是控制台输出给了我这个:

  [ undefined,
  '/',
  'U',
  's',
  'e',
  'r',
  'g',
  'o',
  'n',
  'z',
  'P',
  'j',
  'c',
  't',
  'J',
  'S',
  'a',
  'd',
  'm',
  '-',
  'v',
  'i',
  'l',
  'b',
  '.' ]

我在此处关于堆栈溢出的问题中找到了合并函数,但它正在合并一个数字数组,而我正在合并对象数组。我不知道这是否与我的问题有关。

这是我的源文件之一(另一个遵循相同的模式,但有一些其他电影):

[{
  "title": "Spider-Man: Homecoming",
  "usersScore": "92%",
  "criticsScore": "89%"
}, {
  "title": "Girls Trip",
  "usersScore": "89%",
  "criticsScore": "83%"
}, {
  "title": "Captain Underpants: The First Epic Movie (Captain Underpants)",
  "usersScore": "87%",
  "criticsScore": "62%"
}, {
  "title": "Guardians of the Galaxy Vol. 2",
  "usersScore": "82%",
  "criticsScore": "88%"
}, {
  "title": "Wonder Woman",
  "usersScore": "92%",
  "criticsScore": "89%"
}, {
  "title": "First They Killed My Father",
  "usersScore": "88%",
  "criticsScore": "83%"
}, {
  "title": "Baby Driver",
  "usersScore": "93%",
  "criticsScore": "87%"
}, {
  "title": "Demon",
  "usersScore": "91%",
  "criticsScore": "56%"
}, {
  "title": "The Music of Strangers: Yo-Yo Ma and the Silk Road Ensemble",
  "usersScore": "84%",
  "criticsScore": "85%"
}, {
  "title": "Colossal",
  "usersScore": "80%",
  "criticsScore": "59%"
}, {
  "title": "Certain Women",
  "usersScore": "92%",
  "criticsScore": "51%"
}, {
  "title": "Godzilla Resurgence (Shin Godzilla)",
  "usersScore": "84%",
  "criticsScore": "73%"
}, {
  "title": "My Cousin Rachel",
  "usersScore": "76%",
  "criticsScore": "47%"
}, {
  "title": "The Meyerowitz Stories (New and Selected)",
  "usersScore": "93%",
  "criticsScore": "84%"
}, {
  "title": "Raw",
  "usersScore": "90%",
  "criticsScore": "77%"
}, {
  "title": "The Wedding Plan",
  "usersScore": "86%",
  "criticsScore": "65%"
}, {
  "title": "Maudie",
  "usersScore": "88%",
  "criticsScore": "92%"
}, {
  "title": "Heal the Living (Réparer les vivants)",
  "usersScore": "90%",
  "criticsScore": "70%"
}, {
  "title": "Lady Macbeth",
  "usersScore": "89%",
  "criticsScore": "72%"
}, {
  "title": "The Exception (The Kaiser's Last Kiss)",
  "usersScore": "76%",
  "criticsScore": "67%"
}, {
  "title": "Citizen Jane: Battle for the City",
  "usersScore": "94%",
  "criticsScore": "61%"
}, {
  "title": "The Beguiled",
  "usersScore": "78%",
  "criticsScore": "50%"
}, {
  "title": "The Big Sick",
  "usersScore": "98%",
  "criticsScore": "89%"
}, {
  "title": "The Little Hours",
  "usersScore": "77%",
  "criticsScore": "53%"
}, {
  "title": "A Ghost Story",
  "usersScore": "91%",
  "criticsScore": "66%"
}, {
  "title": "The Hero",
  "usersScore": "77%",
  "criticsScore": "64%"
}, {
  "title": "Megan Leavey",
  "usersScore": "84%",
  "criticsScore": "83%"
}, {
  "title": "Band Aid",
  "usersScore": "85%",
  "criticsScore": "73%"
}, {
  "title": "It Comes At Night",
  "usersScore": "89%",
  "criticsScore": "43%"
}, {
  "title": "The Midwife (Sage femme)",
  "usersScore": "86%",
  "criticsScore": "82%"
}, {
  "title": "Brawl in Cell Block 99",
  "usersScore": "93%",
  "criticsScore": "75%"
}, {
  "title": "Gerald's Game",
  "usersScore": "89%",
  "criticsScore": "78%"
}]

最佳答案

您实际需要的是合并两个数组,然后过滤它们以删除重复项:

const merge = (data1, data2) => {
    // keeps track of already existing titles to avoid duplicates
    let existingIndexes = {};

    // check the the arguments to make sure the code does not break
    data1 = data1 instanceof Array ? data1 : [];
    data2 = data2 instanceof Array ? data2 : [];

    // return a concatenated and filtered copy result
    return data1.concat(data2).filter((movie) => {
        if (existingIndexes.hasOwnProperty(movie.title)) {
            existingIndexes[movie.title] = true;
            return true;
        }
        return false;
    });
};

关于javascript - 如何唯一合并两个 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792007/

相关文章:

javascript - 如何在包含 HTML 的变量中绑定(bind) blob?

java - 如何从扫描仪读取文本文件并转换为 Int 数组 Java

arrays - Mongoose:如何从对象数组中通过多个字段查找

javascript - Kendo Grid with kendo下拉列表

javascript - 通过 axios.get 使用 axios 响应

Javascript 错误 (IE) : Object doesn't support this property or method

比较 char 数组元素

javascript - 如何从该数据结构中获取值

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined

json - 如何使用 Decodable 协议(protocol)为这个 JSON 制作结构?