3

For example,

I have a total of two arrangements.

The key array has keys.

The remaining arrays are multi arrays in one array like [[A], [B], [C], ...]

So how do we put objects in one array?

let key = [“name”, “age”, “country”];

let values = [["james", "23", "US"],["steve", "20", "UK"], ...]


** expect result **
result = [
    {
        "name": "james",
        "age": 23,
        "country": "US"
    },
    {
        "name": "steve",
        "age": 20,
        "country": "UK"
    },
    ...
]


1
  • can be done in a array map and inside do a foreach to create the object to return. you can get access to the array indices from foreach and that index can be used to get the value of the key in keys array Commented Jul 20, 2022 at 6:13

4 Answers 4

1

Single line using array map and reduce functions:

values.map(v=>(key.reduce((acc, k, i) => ({...acc, [k]: v[i]}), {})));

(Note your original question contains non-ASCII quotation marks “” - you need to use " for valid JS syntax).

Sign up to request clarification or add additional context in comments.

Comments

1

if you have data as name age and country with same keys so you can try below code it should work for you.

let values = [["james", "23", "US"],["steve", "20", "UK"], ...]
const result = [];

values.forEach(item => {
    const [name, age, country] = item;
    result.push({ name, age, country });
});

console.log(result)

2 Comments

This is the cleanest approach with O(n) time
Yes if you don't mind hard-coding the keys. OP has specifically provided a keys array...
0

I just asked your question to OpenAI JavaScript Codex and it returned this result.

/* let key = [“name”, “age”, “country”]; */
var key = ["name", "age", "country"];
/* let values = [["james", "23", "US"],["steve", "20", "UK"]] */
var values = [["james", "23", "US"],["steve", "20", "UK"]];
/* So how do we put objects in one array? */
var objects = [];
for (var i = 0; i < values.length; i++) {
  var object = {};
  for (var j = 0; j < key.length; j++) {
    object[key[j]] = values[i][j];
  }
  objects.push(object);
}

I really don't know if it works or not, but I am curious to see what it does. You should try this.

Please forgive me if it doesn't work. Thanks

Comments

0
const objs = values.map(
 (valSet) => 
  Object.fromEntries(
   valSet.map(
    (val,i) => [val,keys[i]]
   )
  )
);

make entry arrays and then use this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.