2

I'm trying to change JSON structure for push to my database

my old JSON :

       [
          {"name": "nameGallery"},
          {"img": "1.jpg"},
          {"img": "2.img"}
       ]

And I want to group "img" variable to "Images" Array like this:

[
  {
    "name": "nameGallery",
    "Images": [
              {"img": "1.jpg"},
              {"img": "2.img"}
              ]
  }
]

I'm trying to use object.assign to manage it but I don't know why it error.

function getData() {
    fetch('text/upload.json').then((res) => res.json())
    .then((data) => {
        console.log(data);
        data = data.map(o => Object.assign({}, o,
        { Images: o.Images.map(({ img }) => ({ img: img })) }
        ));
    })
}

My Result:

enter image description here

Jenwit Virriya
  • 101
  • 1
  • 7
  • Are you sure data has a value? What is console.log(data) showing? – basic Dec 20 '18 at 15:04
  • 3
    @basic it's probably `o.Images` that's `undefined`. – Pointy Dec 20 '18 at 15:05
  • 2
    That's because there is not property called Images in the o object. – asiby Dec 20 '18 at 15:07
  • 1
    Another problem in that you need to show a more realistic data sample that can help someone provide you with a better answer. Can you show the original JSON with more information in the array than just what you have here? – asiby Dec 20 '18 at 15:15
  • @asiby Thank you,next time,I'll care more about realistic data sample. – Jenwit Virriya Dec 20 '18 at 16:02
  • It's alright. I am glad you have found the solution you needed. That's all that matters at the end of the day. – asiby Dec 20 '18 at 21:48

2 Answers2

3

In your solution you are calling .map which will create you one array entry for every array entry in your initial data.

As you described, you expect one object as a result and not an array of object. So look at the following :

const data = [{
    name: 'nameGallery',
  },
  {
    img: '1.jpg',
  },
  {
    img: '2.img',
  },
];

// You want to create a new object using all the others objects
const ret = data.reduce((tmp, x) => {
  // If the key below is 'img', we push the object into 'Images'
  // void 0 means undefined
  if (x.img !== void 0) {
    tmp.Images.push(x);

    return tmp;
  }

  // If the key is not 'img'
  // We copy the keys into tmp
  return {
    ...tmp,

    ...x,
  };
}, {
  // initialize 'Images' key here it won't be undefined
  // when pushing the first data
  Images: [],
});

console.log(ret);
asiby
  • 3,229
  • 29
  • 32
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
-2

You can try something like this:

function getData() {
    fetch('text/upload.json').then((res) => res.json())
    .then((data) => {
        const name = data.find(o => !!o.name);

        return {
          name: name.name,
          Images: data.filter(o => !!o.img)
        };
    })
}
yoavmatchulsky
  • 2,962
  • 1
  • 17
  • 22