如何分组jquery数组

时间:2017-12-08 11:11:10

标签: javascript jquery

我需要将两个数组合并在一起,它们看起来像这样:

var array1 = 
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]

var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]

我想基于x合并它们,其中所有属性都保存在最终对象中。

预期产出:

var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]

我发现$ .extend和$ .merge但是没有成功实现我的需求。有什么指针吗?

4 个答案:

答案 0 :(得分:1)

使用 Object.assign array.prototype.map

var array1 = 
[
  {x: "1/12/2011", y: 4149.9},
  {x: "2/12/2011", y: 4094.5},
  {x: "3/12/2011", y: 3606.8}
];

var array2 =
[
  {x: "1/12/2011", z: 3500},
  {x: "2/12/2011", z: 3600},
  {x: "3/12/2011", z: 3700}
]

var merged = array1.map((e, index) => Object.assign({}, e, array2.find(a => a.x === e.x)));

console.log(merged);

答案 1 :(得分:1)

只需将Object.assign方法与var array1 = [ {x: "1/12/2011", y: 4149.9}, {x: "2/12/2011", y: 4094.5}, {x: "3/12/2011", y: 3606.8} ] var array2 = [ {x: "1/12/2011", z: 3500}, {x: "2/12/2011", z: 3600}, {x: "3/12/2011", z: 3700} ] var expected = array1.map( (a,i) => Object.assign(a, array2.find(b=>b.x == a.x))); console.log(expected);

结合使用即可



<t:inputNumber label="hr.label.LeaveDay" value="#{employeeLeaveHome.entity.leaveDay}"
    decimalPlaces="0"/>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

虽然其余答案几乎是正确的,但他们错过了匹配#include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { if (argc != 2) { return 1; } int n = atoi(argv[1]); vector<double> x; for (int i = 0; i < n; i++) cin >> x[i]; double v = 0; for (int i = 0; i < n; i++) v = 3 * x[i]; cout << v << endl; return 0; }

的重点

&#13;
&#13;
x
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以array#concat您的数组,然后使用array#reduce根据x的值合并它们。

var array1 = [ {x: "1/12/2011", y: 4149.9}, {x: "2/12/2011", y: 4094.5}, {x: "3/12/2011", y: 3606.8} ],
    array2 = [ {x: "1/12/2011", z: 3500}, {x: "2/12/2011", z: 3600}, {x: "3/12/2011", z: 3700} ];

var result = array1
              .concat(array2)
              .reduce((r, o) => {
                r[o.x] = Object.assign({},r[o.x] || {}, o);
                return r;
              },{});
var output = Object.values(result);
console.log(output);