0

I'm getting a request in the following form:

req = {
"id": ["1","2"],
"values": ["fruit", "vegies"]
}

I want to send response as the following:

res = {
"idMap": {
    "1": ["fruit", "veggies"],
    "2": ["fruit", "veggies"]
}
}

I tried using map function but values comes as [Array] and not as ["fruits", "veggies"]. I attach the code below:

const values = req.values
const id = req.id.map((ids) => {
    const idmap = {
        [ids]: values
    }
    return idmap;
});
req = {
    "idMap": id
}

help me with this guys. Thanks in advance..

3
  • should res have the same object reference of the arrays? Commented Jun 12, 2019 at 6:41
  • Your code seems to be working in my console actually. Commented Jun 12, 2019 at 6:44
  • Maybe you also need to JSON.stringify() in your console.log Commented Jun 12, 2019 at 6:59

2 Answers 2

2

You should use reduce for making an object - map returns an array.

const req = {
  "id": ["1", "2"],
  "values": ["fruit", "vegies"]
};

const res = {
  idMap: req.id.reduce((a, c, i) => (a[c] = [...req.values], a), {})
};

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

You could also loop through the array and assign properties of a result object:

const req = {
  "id": ["1", "2"],
  "values": ["fruit", "vegies"]
};

let res = {
  idMap: {}
};

let values = req.values;
req.id.forEach((id, index) => res.idMap[id] = [...values]);

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

3 Comments

i want response as {"1": ["fruits","veggies"], "2": ["fruits","veggies"]}
Oh, I see - my bad @New_Coder.
Fixed @New_Coder - any better?
0

You could generate an object from the mapped entries with (upcoming) Object.fromEntries.

var req = { id: ["1", "2"], values: ["fruit", "vegies"] },
    res = { idMap: Object.fromEntries(req.id.map(k => [k, req.values])) };

console.log(res);

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.