Home > Mobile >  trying to create object inside array of an object react
trying to create object inside array of an object react

Time:09-13

I have tried to research this and i cant seem to figure this out. So i have this function

const addWork = () => {
    setWorkArray([...workArray, { id: uniqid(), company: '', title: '', dateFrom: '', dateTo: '', desc: [], editing: true }]);
};

this adds an object to my workArray, I'm trying to figure out how to add an object to the desc array. I think I'm on the right track I just can't figure out the below function properly.

const addWorkDesc = (itemId) => {
    let f;
    const inOf = workArray.filter((item, index) => {
        f = index;
        return item.id == itemId;
    });
    setWorkArray({ ...workArray, ...workArray[f].desc, desc: [{ id: uniqid(), item: '', editing: true }] });
};

basically the workArray would look like this when im trying to push an object into the desc array

[
   { 
      id: 1asd5y, //generated with uniqid()
      company: 'some company', 
      title: 'peon', 
      dateFrom: 'fall 2012', 
      dateTo: 'spring 2014', 
      desc: [
             { 
                 id: 5d554ty, //generated with uniqid() 
                 item: 'some text here', 
                 editing: true 
              },
              { 
                 id: 9s9d87f, //generated with uniqid() 
                 item: 'some text here', 
                 editing: true 
              },
             ], 
      editing: true 
   },
   { 
      id: 0s09d8f, //generated with uniqid()
      company: 'some company', 
      title: 'peon', 
      dateFrom: 'fall 2012', 
      dateTo: 'spring 2014', 
      desc: [
             { 
                 id: 34kjh5, //generated with uniqid() 
                 item: 'some text here', 
                 editing: true 
              },
              { 
                 id: 77cvb7, //generated with uniqid() 
                 item: 'some text here', 
                 editing: true 
              },
             ], 
      editing: true 
   },
]

CodePudding user response:

So this is less elegant than your solution, but gets the job done.

let workArray = [];

const addWork = () => {
  workArray = [
    ...workArray,
    {
      id: "a",
      company: "",
      title: "",
      dateFrom: "",
      dateTo: "",
      desc: [],
      editing: true,
    },
  ];
};

const addWorkDesc = (itemId) => {
  let newWorkArray = [];
  workArray.forEach((item) => {
    if (item.id === itemId) {
      item.desc.push({ id: "aa", item: "", editing: true });
    }
    newWorkArray.push(item);
  });
  workArray = newWorkArray;
};

addWork();
console.log(workArray);
addWorkDesc("a");
console.log(workArray);

logs -> [
  {
    id: 'a',
    company: '',
    title: '',
    dateFrom: '',
    dateTo: '',
    desc: [],
    editing: true
  }
]

then 

logs -> [
  {
    id: 'a',
    company: '',
    title: '',
    dateFrom: '',
    dateTo: '',
    desc: [ [Object] ],
    editing: true
  }
]
  • Related