Issues with Retrieving Nested Arrays

I am encountering an issue with an object within an array and I am looking to specifically display that as an array.

data1

const data1 = [
  {
    "id": "01",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "fruits"
    }
  },
  {
    "id": "02"",
    "info": ""fefef"&",
    "sub":: ""hieei"&",
    "details"":: {
      "data";: "things"
    }
  }
]

expected output

const final= [
  {
    "data;": "fruits"
  },
  {
    "data": "things"
  }
]

Code

 const final = data.map((data) => { ...data}) 

Answer №1

Iterate through the array and create a fresh object using the details property. It's crucial to return a new object, as failing to do so will result in your new array retaining links to the objects from the original array. Any modifications made to the original array's properties will also be reflected in the new array, which is likely not desired.

const data1=[{id:"01",info:"fefef",sub:"hieei",details:{data:"fruits"}},{id:"02",info:"fefef",sub:"hieei",details:{data:"things"}}];

// Remember to generate a copy of the
// details object; otherwise, changes made to the details
// of the original objects within the array
// will carry over to the mapped array
// since the array objects simply reference the old objects
const out = data1.map(obj => {
  return { ...obj.details };
});

console.log(out);

Answer №2

Iterate over the array and retrieve the details property:

const data = [
  {
    "id": "01",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "fruits"
    }
  },
  {
    "id": "02",
    "info": "fefef",
    "sub": "hieei",
    "details": {
      "data": "things"
    }
  }
]

const result = data.map(item => item.details)

console.log(result)

Answer №3

When you utilize the combination of map and destructuring, the process becomes much simpler.

const data1 = [
  {
    id: "01",
    info: "fefef",
    sub: "hieei",
    details: {
      data: "fruits",
    },
  },
  {
    id: "02",
    info: "fefef",
    sub: "hieei",
    details: {
      data: "things",
    },
  },
];

const res = data1.map(({ details: { data } }) => ({ data }));

console.log(res);

// If only the details object is required

const res2 = data1.map(({ details }) => details);

console.log(res2);

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

Contrast two arrays using Ruby and generate a new array consisting of elements from both arrays

I have a dilemma involving two arrays, array1 and array2. My goal is to compare these arrays and generate a third array, array3, that includes elements from array2 which are not present in array1. Here's what I've attempted so far: my_buckets = ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Encountered an issue with accessing the property 'path' of undefined in nodejs

Below is my server side code snippet: var fs = require('fs'), MongoClient = require('mongodb').MongoClient, db; var url = "mongodb://localhost:27017/fullwardrobedb"; MongoClient.connect(url, {native_parser: true}, function (err, connec ...

Receive a condensed version of several scripts

My shop's category pages display a list of products, and I need to change the position of a wishlist button for each product on the list. To achieve this, I created individual jQuery scripts for each product like so: jQuery('.product:nth-child( ...

Setting up a plan for executing Javascript server side scripts

Can JavaScript be executed server-side? If I attempt to access a script , can it be scheduled to run every four hours? Would most web hosts allow this, or is it considered poor webmaster practice? The main goal is to activate my website's webcrawler/ ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Ways to postpone a for loop in Jquery

Currently, I am working on creating an image gallery using a for loop to load all the images. However, I am facing an issue where the loop is running too fast, and I would like to add a delay after each iteration. I attempted to use a timeout function, bu ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

Ways to ensure that the form data stays consistent and visible to the user continuously

Is there a way to ensure that the user submits the form, stores it in a MYSQL database, and then displays the same submitted data in the form field? <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</l ...

The $http service encounters an error while attempting to retrieve a JSON file from the server

When attempting to fetch a file from the server, I utilize the $http service in the following manner: $http({url: url, method: "GET", withCredentials: true}); For some mysterious reason, an exception is only thrown when trying to retrieve JSON files from ...

When using selenium with python, the function excecute_script('return variable') may not technically return variables, even though the variable does exist

My attempt to retrieve a variable from javascript code using selenium is encountering difficulties. Despite the presence of the variable (confirmed by inspecting the source code before executing the script), the command driver.execute_script('return v ...

Converting an AngularJS Array to Firebase JSON Format

Currently, in my application, I am working on creating an array using JS. $scope.items = []; As I add items to this array, I retrieve information from a Firebase Reference and populate the items array with it. es.addItem = function(item){ var produc ...

What is the procedure for collapsing a table row or grid?

Looking at this image, I'm trying to find a way to collapse the breakfast row. Any ideas on how I can collapse either the entire tr or with a div? ...

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...