【问题标题】:Adding object properties from one JSON data file to another将对象属性从一个 JSON 数据文件添加到另一个
【发布时间】:2014-12-04 22:42:21
【问题描述】:

我有两个本地 JSON 文件。我想将一个文件中一个对象的属性添加到另一个文件中的对应对象中。

这是一个例子..

数组1:

[
  {
    "id": 1,
    "username": "Joe Smith",
    "pic": "images/profile/Joe_smith.jpg"
  },
  {
    "id": 2,
    "username": "Jane Smith",
    "pic": "images/profile/Jane_smith.jpg"
  }
 ]

数组2:

[
 {
   "id": 3,
   "userId": 1,
   "profession": "dentist"
 },
 { 
   "id": 4,
   "userId": 2,
   "profession": "pilot"
 }

想法是将 Array1 中的“pic”属性添加到 Array2 中的正确对象。如果 Array1 中的 id 与 Array2 中的 userId 匹配,则匹配正确。 Array2 最终看起来像这样:

[
 {
   "id": 3,
   "userId": 1,
   "profession": "dentist",
   "pic": "images/profile/Joe_smith.jpg"
 },
 { 
   "id": 4,
   "userId": 2,
   "profession": "pilot",
   "pic": "images/profile/Jane_smith.jpg"
 }

之后,我将使用 angular 来显示带有脸部的名称。希望我解释清楚。任何帮助将不胜感激!

【问题讨论】:

  • 看起来就像解析 JSON、遍历两个数组并合并各个对象一样简单。你有什么特别的问题吗?你知道如何解析 JSON 吗?如何遍历数组?
  • 我知道如何遍历数组,在这种情况下我可能需要做两次。不过,解析对我来说是新事物。
  • 感谢费利克斯

标签: javascript arrays json angularjs


【解决方案1】:

只是为了好玩。在这个例子中使用https://lodash.com

var people = [
    { "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" }, 
    { "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
    { "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];

var professions = [
    { "id": 3, "userId": 1, "profession": "dentist" },
    { "id": 4, "userId": 2, "profession": "pilot" }
];

var workers = _.map(people, function(human) {
    var work = _.findWhere(professions, { 'userId': human.id });
    return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});

console.log(workers);

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 2012-06-30
    • 2020-11-14
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多