-3

I need to change JSON.

Example of my JSON array:

{
    // ...any properties
    point: [
      location: {
        latitude: 0,
        longitude: 0 
      },
      name: "Point1",
      pointId: 1
    ]
}

And I loop through the array:

data.points.forEach((formData: IAddress) => {
  control.push(this.initiateForm(formData));
});

The obtained result is:

{
    location: {
      latitude: 0,
      longitude: 0 
    },
    name: "Point1",
    pointId: 1
}

The desired result is:

{
  latitude: 0,
  longitude: 0  
  name: "Point1",
  pointId: 1
}

Just remove location JSON as if to eject longitude and latitude from the location.

TylerH
  • 20,799
  • 66
  • 75
  • 101

3 Answers3

0

You can use Array.map, object destructuring and spread:

const original = {
    // ...any properties
    // Here, I assume the `points` is an array of objects instead of a buggy array/object
    points: [
      {
        location: {
          latitude: 0,
          longitude: 0 
        },
        name: "Point1",
        pointId: 1
      }
    ]
};

const result = original.points
  .map( ({location, ...rest}) => ({
    ...rest,
    ...location,
  }))
emi
  • 2,786
  • 1
  • 16
  • 24
0

You can do a bit of work with Object.entries, Object.fromEntries and the spread (...) operator:

const points =  [{
      location: {
        latitude: 0,
        longitude: 0 
      },
      name: "Point1",
      pointId: 1
    }];


const result = points.map(p => {
  return {
    ...Object.fromEntries(Object.entries(p).filter(e =>  e[0] != "location")),
    ...p.location
  };
});
console.log(result)
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • this is got me error Property 'fromEntries' does not exist on type 'ObjectConstructor'.ts(2339) – Michael Tomas Mar 05 '21 at 15:06
  • 1
    @MichaelTomas `Object.fromEntries` is standard javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries – Jamiec Mar 05 '21 at 15:46
0

Flatten for objects

you want something like flatten but on object, so quickly I made some code do it.

without specifing the key (using typeof), but only one level object.

const arr = [
  {
    "location": {
      "latitude": 0,
      "longitude": 0
    },
    "name": "Point1",
    "pointId": 1,
    "extraObject": {
      "one": "value1",
      "two": "value2"
    }
  },
  {
    "location": {
      "latitude": 0,
      "longitude": 0
    },
    "name": "Point1",
    "pointId": 1
  }
]


const newArr = arr.map(item => {
  return Object.keys(item).reduce((acc, key) => {
    if (typeof item[key] === 'object') {
      acc = {...acc, ...item[key]};
    } else {
      acc[key] = item[key];
    }
    return acc;
  }, {})
})

console.log(newArr);
Omer
  • 3,232
  • 1
  • 19
  • 19