简体   繁体   中英

New array of objects based on an array inside an object?

need to create a shallow array of objects based on the elements of an array that is an object's value:

var obj = {
  a: 1,
  b: 'x',
  c: 'z',
  d: ['rr', 'qq']
};

var rec = [];

obj.d.forEach(function(e, i) {
  rec.push({
    d: e
  })
});

console.log(rec);

But of course this only gets me

[ { d: 'rr' }, { d: 'qq' } ]

How to get to this in a new array of objects? -->

[ { a: 1,
    b: 'x',
    c: 'z',
    d: 'rr' }, 
  { a: 1,
    b: 'x',
    c: 'z',
    d: 'qq' } ]

The easiest way to get the desired result would be to use the map function (which maps elements of one array to a new array using a given mapping function). You can then create new objects re-using a , b , and c from the original object and d from the mapping function parameters:

var rec = obj.d.map(function(r) {
  return { 
    a: obj.a, 
    b: obj.b, 
    c: obj.c, 
    d: r 
  };
});
obj.d.forEach(function(e) {
    var item = {};

    Object.keys(obj).forEach(function(key) {
        item[key] = obj[key];
    });

    item.d = e;

    rec.push(item);
});

But properties a, b, c can't be objects. Otherwise each item in the rec array will have the same reference.

Alternately, this works, but it is quite ugly:

var o = {
  a: 1,
  b: 'x',
  c: 'z',
  d: ['rr', 'qq']
};

var arr = [];

Object.keys(o).forEach(function(k) {
    var val = o[k];
    if (Array.isArray(val)) {
        val.forEach(function(j) {
        arr.push({[k] : j});
        });
    }
});

arr.forEach(function(obj) {
    for (var p in o) {
        var val = o[p];
        if (!Array.isArray(val)) {
        obj[p] = val
        }
    }
});

console.log(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM