Fiyin Akinsiku
Fiyin Akinsiku

Reputation: 188

How to assign an object /array to another object?

I am working on a function that takes in a list like this:

const payload = [
    [1, 2],
    [1,2,3],
    {
        name: 'sandra',
        age: 20,
        email: '[email protected]'
    }
]

and returns an object like this:

{
  name: 'return payload',
  response: [ 
    { arr: [1, 2] }, 
    { arr: [1, 2, 3] }, 
    { arr: {
      name: 'sandra',
      age: 20,
      email: '[email protected]'
    }
  ]
}

This is the function I have:

const returnPayload = (arr) => {
  let response = [];
    for(let i = 0; i < arr.length; i++) {
      response.push({arr: arr[i]})
    }
    return {"name": "return payload", "response": response}
}

returnPayload(payload);
console.log(returnPayload(payload))

and this is what it currently returns:

{
  name: 'return payload',
  response: [ { arr: [Array] }, { arr: [Array] }, { arr: [Object] } ]
}

I have checked several solutions online and the recommendations are to pass the returning object into JSON.stringify(obj), but I am looking for a neater and easier-to-read alternative. The JSON method returns this:

{"name":"return payload","response":[{"arr":[1,2]},{"arr":[1,2,3]},{"arr":{"name":"sandra","age":20,"email":"[email protected]"}}]}

Pls forgive the title, I'm not sure how to describe this issue.

Upvotes: 1

Views: 70

Answers (2)

charmful0x
charmful0x

Reputation: 153

if by "easy-to-read" you mean how to see the result, you can continue with JSON.stringify() but add an additional argument for spacing.

const payload = [
    [1, 2],
    [1,2,3],
    {
        name: 'sandra',
        age: 20,
        email: '[email protected]'
    }
]

const returnPayload = (arr) => {
  let response = [];
    for(let i = 0; i < arr.length; i++) {
      response.push({arr: arr[i]})
    }
    return {"name": "return payload", "response": response}
}

returnPayload(payload);
console.log(JSON.stringify(returnPayload(payload), null, 3))

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370789

Sounds like you just need to map the array and return an object containing each item in the callback:

const payload = [
    [1, 2],
    [1,2,3],
    {
        name: 'sandra',
        age: 20,
        email: '[email protected]'
    }
];

const result = {
  name: 'return payload',
  response: payload.map(item => ({ arr: item }))
};
console.log(result);

(but the arr property is not necessarily an array, as you can see by the 3rd item - consider a more informative property name, perhaps?)

Upvotes: 1

Related Questions