Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property.

Here is the JSON array I am working with:

[{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position:{lat: 59.441388, lng: 10.579491}
time:"15-05-2016"
type:"Teine"
userId:""
},
{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position:{lat: 59.441388, lng: 10.579491}
time:"15-05-2016"
type:"Teine"
userId:""
}]

I am looking for an output in the following format:

[{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position.lat:59.441388, 
position.lng: 10.579491,
time:"15-05-2016"
type:"Teine"
userId:""
},
{
amount:"1 teine med 110 mtr iletau"
comment:""
created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)"
locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden)."
position.lat: 59.441388, 
position.lng: 10.579491,
time:"15-05-2016"
type:"Teine"
userId:""
}]

If anyone can provide suggestions on how to achieve this desired output using JavaScript, I would greatly appreciate it.

Answer №1

To create new properties in the array, iterate through it and remove the existing position.

var array = [{ amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }, { amount: "1 teine med 110 mtr iletau", comment: "", created: "Tue May 17 2016 00:00:00 (W. Europe Standard Time)", locationDescription: "På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).", position: { lat: 59.441388, lng: 10.579491 }, time: "15-05-2016", type: "Teine", userId: "" }];

array.forEach(o => {
    Object.assign(o, { 'position.lat': o.position.lat, 'position.lng': o.position.lng });
    delete o.position;
});

console.log(array);

Answer №2

One clever method is to implement recursion for a flexible approach. This technique involves the function calling itself to traverse through the object structure:

$ cat example.js && echo "\n-------\n" && node example.js
const data = {x:1, y:2, z:{w:3, s:{t:4, u:5}}};

function flattenObject (obj){
  const result = {};
  Object.keys(obj).forEach(key => {
    const value = obj[key];
    if (typeof value === 'object') {
      const flattened = flattenObject(value);
      Object.keys(flattened).forEach( subKey => {
         result[`${key}.${subKey}`] = flattened[subKey]
      })
    } else {
      result[key] = value
    }
  });
  return result;
}

console.log(JSON.stringify(flattenObject(data), null, 2));

-------

{
  "x": 1,
  "y": 2,
  "z.w": 3,
  "z.s.t": 4,
  "z.s.u": 5
}

Answer №3

or utilize Array.map()

const arr = [
{
  amount:"1 teine med 110 mtr iletau",
  comment:"",
  created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)",
  locationDescription:"På vestsiden av Jeløya, utenfor Moss. (Oslofjorden).",
  position:{lat: 59.441388, lng: 10.579491},
  time:"15-05-2016",
  type:"Teine",
  userId:""
},
{
  amount:"1 teine med 110 mtr iletau",
  comment:"",
  created:"Tue May 17 2016 00:00:00 (W. Europe Standard Time)",
  locationDescription:"På vestsiden av Jeløya, utenfor Moss.(Oslofjorden).",
  position:{lat: 59.441388, lng: 10.579491},
  time:"15-05-2016",
  type:"Teine",
  userId:""
}
];


const flattenPositions = o => {
  o["position.lng"] = o.position.lng;
  o["position.lat"] =  o.position.lat;
  delete o.position;
  return o;
 };

arr = arr.map(el=>flattenPositions(el));


console.log(arr);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Occasions focused on the <input type="file"> feature

Looking for a way to write a file input in React that accepts CSV files, validates them, and prevents upload if there are errors? Check out the code snippet below: <CustomInput type="file" id="fileBrowser" name="file" label={filename || 'Choos ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

Is there a way in MVC3 / .net4 to convert a JSON formatted JavaScript array into a C# string array?

I am facing a challenge with my MVC3/.Net service where it is receiving arguments in the form of a JSONified Javascript array. I want to convert them into a C# array of strings. Is there a built-in solution available for this task, or do I need to create ...

Using JavaScript to dynamically insert HTML content and create a toggle effect

Within a div, I have a collection of large images that I am attempting to insert into another div using JavaScript toggle functionality. Please test the code snippet provided below. $(".toggleimages").on("click", function(e) { e.preventDefault(); ...

Tips for implementing the f11 effect with a delay of 5 seconds after pressing a key in JavaScript or jQuery

Is there a way to activate the F11 effect only 5 seconds after pressing a key using JavaScript or jQuery? ...

Incorporating Functions from an External Script in ReactJS/GatsbyJS

One of the functionalities on my website involves dynamically inserting a script into the head when a form element is focused, enabling it to load faster. This process is achieved using basic vanilla JS rather than React Helmet, as shown below: const handl ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

Enhance your Verold model object with engaging animations

Trying to utilize verold for animating 3D models through a script has been challenging. The proper usage of the verold API components seems unclear at the moment. A model has been successfully loaded into the scene with a script attached as an attribute o ...

acquiring JSON information from different domains

I am in need of creating an ajax request to fetch JSON data from a RESTful Web Service that is hosted on a different domain (KARAF using cxf). The client making the ajax call is situated on a separate domain (Apache Tomcat). The Web Service responds with ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Form validation in AngularJS for controllers with multiple instances

My specific needs In order to meet the unique requirements of my business, manual validation is necessary. The validation rules can vary in strictness depending on the context in which a specific screen is accessed. It is also important to note that ther ...

bespoke slickgrid dropdown editor

I am currently working on implementing a slickgrid feature where a cell needs to display a dropdown (selectlist) with values fetched from a restful service. These values will vary for each row. The requirement is that the user should be able to select one ...

Step-by-step guide: Assigning a color to a card element in MaterializeCSS

I am currently working on a project using Vue.js where I want to display colored cards from MaterializeCSS. The colors are stored as hex codes in a separate database and are part of items looped through with the v-for loop, like this: <div ...

Component in Angular with an empty variable in TypeScript

I'm encountering an issue on my web page where I have a loop calling a component multiple times. I successfully pass data to the component, but the problem arises when I try to display the value of an object in the component. In the component's H ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

How can I apply a texture to a 3D rectangle in THREE.js?

I am attempting to create a 3D box in THREE.js that represents a box made up of 2x4 Legos, measuring 24 pieces wide by 48 pieces long and an unspecified number of pieces tall. I have created a texture displaying this pattern using random colors: https://i ...