-1

I have two objects are contained by an array for each. The following code works. However, I am feeling this code I wrote is a bit odd. I am seeking a better or more standard way to improve below code. Thanks

  const a = [
    {
      apple: '1',
      banana: '2',
    },
  ];

   const b = [
    {
      apples: '1',
      bananas: '2',
    },
  ];

  const json1 = JSON.parse(JSON.stringify(...a));
  const json2 = JSON.parse(JSON.stringify(...b));

  console.log({ ...{a: json1}, ...{b: json2}})

the output needs to be

{
  "a": {
    "apple": "1",
    "banana": "2"
  },
  "b": {
    "apples": "1",
    "bananas": "2"
  }
}

Edit: Sorry I forgot to mention previously, I don't want a[0] b[0]

olo
  • 5,225
  • 15
  • 52
  • 92

3 Answers3

1

You could get an object for each array and assign to the wanted properties.

const
    a = [{ apple: '1', banana: '2' }],
    b = [{ apples: '1', bananas: '2' }],
    result = { a: Object.assign({}, ...a), b: Object.assign({}, ...b) };

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can achieve the same result with

const a = [{
  apple: '1',
  banana: '2',
}];

const b = [{
  apples: '1',
  bananas: '2',
}];

console.log({ a: a[0], b: b[0] })
0

If your current code is giving you the result you want, then you can just do this:

const result = {a, b};

Live Example:

const a = [
    {
      apple: '1',
      banana: '2',
    },
  ];

   const b = [
    {
      apples: '1',
      bananas: '2',
    },
];

const result = {a, b};
console.log(result);

If you want to make copies of the objects, you can do this:

const result = {
    a: a.map(o => ({...o})),
    b: b.map(o => ({...o})),
};

Live Example:

const a = [
    {
      apple: '1',
      banana: '2',
    },
  ];

   const b = [
    {
      apples: '1',
      bananas: '2',
    },
];

const result = {
    a: a.map(o => ({...o})),
    b: b.map(o => ({...o})),
};
console.log(result);

Or for a more generic deep copy operation, see this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875