0

I am learning React and came across a slightly tricky problem for my level. From my API call I get a response which is an array of objects. I want to submit data add some object data . To get the idea of how the response looks, this is an example (it is array of JSON) some data want to spread in array object data {school:"test",schoolId:"2"}

Response

data = [
  {0: {name: "tom"}},
  {1: {name: "Pope"}},
  {2: {name: "jack"}}
 ];


Response to want send like
data = [
   {
name: "tom",
school :"testing",
schoolId:"2"
},
   {
name: "Pope",
school :"testing",
schoolId:"2"},
   {
name: "jack",
school :"testing",
schoolId:"2"}
 ];
1
  • 1
    Just use .map on your data.. data.map(item => ({...wrapper, item})) where wrapper = { school: 'testing'. schoolOd: 2} Commented Jul 20, 2021 at 15:32

1 Answer 1

2

Use .map on your original array..

Define your object which you want to merge (eg: wrapper) and so a simple spread on it inside .map

const data = [
  {name: "tom"},
  {name: "Pope"},
  {name: "jack"}
];

const wrapper = {
  school: 'testing',
  schoolId: 2
};

const result = data.map(item => ({...wrapper, ...item}));

console.log(result);

/*
[
  { school: 'testing', schoolId: 2, name: 'tom' },
  { school: 'testing', schoolId: 2, name: 'Pope' },
  { school: 'testing', schoolId: 2, name: 'jack' }
]
*/

Live version

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

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.