Home > OS >  Push array values to another array with a Key [closed]
Push array values to another array with a Key [closed]

Time:09-22

I have a question regarding arrays in javascript. Here I have 2 arrays, which needs to be appended together like shown in the last array example.

One array has a key value pair, while the second array is just has values.

Here at first the key should be added to the 2nd Array. And the same array should be merged with the 1st array for each values it has in its array.

1st Array

[
$subtask_assigned_to: "rohit"
status: 0
subtask_description: "described something"
]

2nd Array

[
0: "value 1"
1: "value 2"
]

Now I want to merge the top 2 Arrays and want a result of arrays like shown below with a key(subtask_name) added to the second array.

[
 subtask_name: "value 1"
 subtask_assigned_to: "rohit"
 status: 0
 subtask_description: "described something"
]

[
 subtask_name: "value 2"
 subtask_assigned_to: "rohit"
 status: 0
 subtask_description: "described something"
]

And this has to achieved in Javascript. Thank you for your solutions.

CodePudding user response:

Just so you know, an "array" as you call it with named keys is an Object--it's not an Array in Javascript terminology. An Array in Javascript is a specific type of Object with strictly numeric keys.

Nitpicks aside, you can just use a map and the spread operator to clone the object and add the extra subtask_name key.

Here's an even simpler version. Credit: Robby Cornelissen

const obj = {
  $subtask_assigned_to: "rohit",
  status: 0,
  subtask_description: "",
};

const arr = [
  "value 1",
  "value 2"
];

const converted = arr.map(subtask_name => ({...obj, subtask_name}));

console.log(converted);

  • Related