如何使用sailsjs-nodejs连接/合并两个json对象

时间:2016-08-06 13:49:00

标签: javascript json node.js express sails.js

您好我是Sailsjs-Nodejs的新手。在我的控制器中,我有两个JSON对象,我需要合并/加入,所以我可以使第三个发送响应

res.send(obj1)输出

public class ThreadStaticTest implements Runnable {

    static int i = 5;

    public static void main(String[] args) {
        ThreadStaticTest obj = new ThreadStaticTest();
        Thread t1 = new Thread(obj);
        Thread t2 = new Thread(obj);
        Thread t3 = new Thread(obj);

        t1.setName("A");
        t2.setName("B");
        t3.setName("C");

        t1.start();
        t2.start();
        t3.start();
    }

    @Override
    public void run() {
        i++;
        System.out.println(Thread.currentThread().getName()+" : "+i);
    }
}

res.send(obj2)输出

[
  {
    total_fare: "376",
    arrival_to: "ABV"
  },
  {
    total_fare: "312",
    arrival_to: "ACC"
  },
  {
    total_fare: "432",
    arrival_to: "BFN"
  }
]

这是我的预期结果 res.send(obj3)应该输出

[
  {
    url: "nigeria.php",
    country: "Nigeria",
    city_code: "ABV"
  },
  {
    url: "ghana.php",
    country: "Ghana",
    city_code: "ACC"
  },
  {
    url: "south-africa.php",
    country: "South Africa",
    city_code: "BFN"
  }
]

2 个答案:

答案 0 :(得分:1)

您可以在不修改源数组的情况下执行以下操作;



var arr = [{total_fare: "376",arrival_to: "ABV"},
           {total_fare: "312",arrival_to: "ACC"},
           {total_fare: "432",arrival_to: "BFN"}],
    brr = [{url: "nigeria.php",country: "Nigeria",city_code: "ABV"},
           {url: "ghana.php",country: "Ghana",city_code: "ACC"},
           {url: "south-africa.php",country: "South Africa",city_code: "BFN"}],
 merged = arr.map((o,i) => Object.assign({},o,brr[i]));
 console.log(merged);




答案 1 :(得分:0)

检查此示例。

使用lodash套餐我使用_.map()来查看总票价, 并使用_.find()arrival_to == city_code找到第一次发生,并_.extend()加入对象。


当您的对象数组不顺序时,以及比国家/地区列表中的元素更多的总票价时,此示例很有用。

我特意添加{total_fare: "111",arrival_to: "ACC"}以显示您和示例,当有2个或更多对象具有相同的arrival_to字段时。



// const _ = require('lodash'); //uncomment on serverside usage

let totalFares = [{total_fare: "376",arrival_to: "ABV"},
           {total_fare: "312",arrival_to: "ACC"},
           {total_fare: "432",arrival_to: "BFN"},
           {total_fare: "111",arrival_to: "ACC"}];

let countries = 
           [{url: "nigeria.php",country: "Nigeria",city_code: "ABV"},
           {url: "ghana.php",country: "Ghana",city_code: "ACC"},
           {url: "south-africa.php",country: "South Africa",city_code: "BFN"}];

totalFares = _.map(totalFares, (totalFare) => {
    _.extend(totalFare, _.find(countries, 
                              (country) => 
                               country.city_code == totalFare.arrival_to));

    return totalFare;
});

console.log(totalFares);

<script src="https://raw.githubusercontent.com/lodash/lodash/4.14.1/dist/lodash.js"></script>
&#13;
&#13;
&#13;