Utilizing ES6, accessing the first element of an array of objects

How can I access the values of the first or a specific object in an array based on an index using ES6?

arrayOne =[
    { child: [
      {e1: 'ABCD', e2: 'BCDF'}, 
      {e1: '1234', e2: '5689'}, 
      {e1: 'QAZX', e2: 'WESD'}]},
    { child: [
      {e1: 'UHYT', e2: 'QYDG'}, 
      {e1: '9568', e2: '4587'}, 
      {e1: 'ISSF', e2: 'QEIR'}
    ]}
  ]

The desired output is

arrayTwo = [['ABCD', 'BCDF'], ['1234', '5689'], ['QAZX', 'WESD']]'

Additionally, how do I ensure my code remains dynamic if there are changes to variable names like 'child' or 'e1' or 'e2'?

Answer №1

1) To achieve the desired result, utilize the map function

arrayOne[0].child.map(({ e1, e2 }) => [e1, e2]);

or

const arrayOne = [
  {
    child: [
      { e1: "ABCD", e2: "BCDF" },
      { e1: "1234", e2: "5689" },
      { e1: "QAZX", e2: "WESD" },
    ],
  },
  {
    child: [
      { e1: "UHYT", e2: "QYDG" },
      { e1: "9568", e2: "4587" },
      { e1: "ISSF", e2: "QEIR" },
    ],
  },
];

const result = arrayOne[0].child.map((o) => [o.e1, o.e2]);
console.log(result);

2) If you wish to extract all values from the child array elements(objects) and store them in an array, you can make it generic as

const arrayOne = [
  {
    child: [
      { e1: "ABCD", e2: "BCDF" },
      { e1: "1234", e2: "5689" },
      { e1: "QAZX", e2: "WESD" },
    ],
  },
  {
    child: [
      { e1: "UHYT", e2: "QYDG" },
      { e1: "9568", e2: "4587" },
      { e1: "ISSF", e2: "QEIR" },
    ],
  },
];

const result = arrayOne[0].child.map((o) => Object.values(o));
console.log(result);

3) In cases where the object key is unknown

const arrayOne = [
  {
    child: [
      { e1: "ABCD", e2: "BCDF" },
      { e1: "1234", e2: "5689" },
      { e1: "QAZX", e2: "WESD" },
    ],
    child2: [
      { e1: "UHYT1", e2: "QYDG1" },
      { e1: "95681", e2: "45871" },
      { e1: "ISSF1", e2: "QEIR1" },
    ],
  },
  {
    child: [
      { e1: "UHYT", e2: "QYDG" },
      { e1: "9568", e2: "4587" },
      { e1: "ISSF", e2: "QEIR" },
    ],
  },
];
const result = Object.values(arrayOne[0]).flatMap((value) => value.map((o) => Object.values(o)));
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

// Here is a solution based on index values

arrayOne =[
    { child: [
      {e1: 'ABCD', e2: 'BCDF'}, 
      {e1: '1234', e2: '5689'}, 
      {e1: 'QAZX', e2: 'WESD'}]},
    { child: [
      {e1: 'UHYT', e2: 'QYDG'}, 
      {e1: '9568', e2: '4587'}, 
      {e1: 'ISSF', e2: 'QEIR'}
    ]}
  ]
// Desired output based on the provided index, with dynamic e1 and e2 values
arrayTwo = [['ABCD', 'BCDF'], ['1234', '5689'], ['QAZX', 'WESD']];

const getValueByIndex = (index) => Object.values(arrayOne[index])[0].map(o =>  Object.values(o));
console.log(getValueByIndex(0));

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

Convert the existing jQuery function to Angular 9 syntax

I have just started learning Angular and am finding it challenging to rewrite a jQuery code that I use for loading the "classycountdown" script. Below is the jQuery function that I need to convert: $(document).ready(function() { var remainingSec = $(& ...

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

I am seeking to enable a specific div when the crawler condition is met

This specific div houses the character and becomes active when the character is clicked. Upon clicking, a jQuery function is triggered to display other countries. //this particular div should remain active when the crawler condition is met. It displays th ...

When it comes to retrieving values from JSON objects in JavaScript, one of two identical objects will return the expected values while the other may

I encountered a perplexing issue with two identical JSON objects. When I use JSON.stringify(obj1) == JSON.stringify(obj2), it returns true. Despite both objects being accessible and inspectable in the console, I'm facing difficulty accessing the valu ...

Creating dynamic and interactive web pages can be achieved by utilizing either $_POST or $_GET with Modal,

In the snippet below, you'll find the HTML code that pulls an array of 6 objects from a database and displays them in a Bootstrap row successfully. <div class="row products"> <?php while($product = mysqli_fetch_assoc($featured)) ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Issue encountered while attempting to generate a Jquery button

I seem to be facing some difficulties as I have successfully completed this task before. Currently, I am dynamically adding HTML code: ...<td><label><input type=\"checkbox\" checked=\"checked\" class=\"Activechk fo ...

Utilizing the forEach method for decision-making

Here is an array called 'array' with values [10, 15, 20] var array = [10, 15, 20]; There is also a variable named N with a value of 20: var N = 20; I need to iterate through the array and check if N is greater than all numbers in the array in ...

Can Django capture and store the name of the active user's logged-in browser in the database?

In Django, we already have session details stored in django_session and last_login in the auth_user table. However, I am interested in storing the browser name when a user logs in using their browser in the database. Currently, I can retrieve the browser ...

Having difficulty extracting only names from the database with mongoose

My goal is to retrieve the value of all the name keys stored in my database. Each document in the database has only one key, which is the "name" key. Below is the code snippet that I need assistance with: user.find({}, 'name', function(err, user ...

How can I format the input type number with a thousand separator as 123.456.789?

When entering the number 123456, I want to see 123.456 displayed in the input field. I tried using my code, but it displays 123,456 instead. Is there a way to ensure that the thousand separator is a dot and not a comma? You can view my code at this link ...

methods for merging and flattening arrays in php

Hello, I recently wrote this code in Laravel: return [ 'image' => $this->image, $this->categories()->get()->map(function ($category) { return [ $category->name => $category->pivot->image ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Understanding the lockfile: deciphering the significance of each line in the yarn.lock file

I'm curious about the meaning of each line in this file. I encountered issues with packages due to dependencies in my project. After upgrading nuxt from version 1x to 2x, all tests started failing. After spending hours searching online, I discovered ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

Trouble loading Styled Components in React Typescript with Webpack configuration

Hey there! I'm diving into the world of styled components for the first time, and I'm a bit lost on where I might have slipped up. I've got my webpack all sorted out and my .babelrc file in place. As I was going through the Styled Component ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

Assign a value to a variable using a function in Typescript

Is there a way in typescript to explicitly indicate that a function is responsible for assigning value to a variable? UPDATED CODE Here, the code has been simplified. While getText() ensures that it will never be undefined, this may not hold true in subs ...

I'm attempting to showcase the input provided by the user using an array, but I'm struggling to find the solution

Once the user enters a number, the output should display it. For example: "Please enter your number: 1 2 3 4." The original array will then be shown as: 1 2 3 4. I attempted to use a for loop to handle the user input and display the numbers in num, but I ...