How to Access Values from Nested Arrays in JavaScript Without Using Specific Keys

I am currently working on a function that will return an object with certain keys omitted from a potentially nested structure within an array. While I came across a similar solution in another thread, it didn't quite fit my requirements. Below is the code snippet I am experimenting with:

function omit(obj, keys) {
    let newObj = [];
    for (let i of obj) {
        if (i === keys) {
            //do nothing
        } else {
            //newObj.push[i]; nope?
            return newObj;
        }
        //return newObj;
    }
}

EDIT: Here is the formula along with some sample input and output;

var x = {
    key1: true,
    key2: 2,
    key3: {
        nested1: 'JavaScript'
    }
};

omit(x, ['key2', 'key3']) ==> {
    key1: true
}

omit(x, ['nested1']) ==> {
    key1: true,
    key2: 2,
    key3: ''
}

Answer №1

It seems like you're trying to scan through an array, filtering out certain values and possibly navigating through nested arrays within it. The solution lies in recursion. Let's start by understanding how to filter out specific keys from an array:

function omitFromArray(array, valuesToOmit) {
  const newArray = [];
  for (const value of array) {
    if (valuesToOmit.indexOf(value) === -1) {
      newArray.push(value);
    }
  }
  return newArray;
}

const arrayToTest = [1, 2, 3, 4, 5, 6];
const testValuesToOmit = [1, 4, 6];

console.log(omitFromArray(arrayToTest, testValuesToOmit));
// returns [2, 3, 5]

While this method works for flat arrays, we need a recursive approach to handle nested arrays efficiently. Here's an example of how that can be achieved:

function omitFromNestedArray(array, valuesToOmit) {
  function walk(array, valuesToOmit) {
    const newArray = [];
    for (const value of array) {
      if (Array.isArray(value)) {
        newArray.push(walk(value, valuesToOmit));
      } else {
        if (valuesToOmit.indexOf(value) === -1) {
          newArray.push(value);
        }
      }
    }
    return newArray;
  }
  return walk(array, valuesToOmit);
}

const nestedArrayToTest = [1, 2, [3, [4, 5], 6], 7];
const testValuesToOmit = [1, 4, 6];

console.log(omitFromNestedArray(nestedArrayToTest, testValuesToOmit));
// returns [2, [3, [5]], 7]

This recursive function delves into nested arrays, handling each level appropriately until the desired output is obtained. Feel free to ask if you have any questions!

EDIT: To adapt the code for objects instead of arrays, check out this snippet:

function removeUnwantedKeysFromObject(obj, unwantedKeys) {
  function walk(obj, unwantedKeys) {
    for (const key of Object.keys(obj)) {
      const value = obj[key];
      if (typeof value === 'object') {
        walk(value, unwantedKeys);
      }
      if (unwantedKeys.indexOf(key) !== -1) {
        delete obj[key];
      }
    }
  }
  walk(obj, unwantedKeys);
}

let objectToTest = {key1: true, key2: 2, key3: { nested1: 'JavaScript' }};
removeUnwantedKeysFromObject(objectToTest, ['key2', 'key3']);
console.log(objectToTest);
// returns { key1: true }
objectToTest = {key1: true, key2: 2, key3: { nested1: 'JavaScript' }};
removeUnwantedKeysFromObject(objectToTest, ['nested1']);
console.log(objectToTest);
// returns { key1: true, key2: 2, key3: {} }

Keep in mind that this code modifies the original object. If you require a new object, you'll need to adjust the code accordingly or utilize a library for deep cloning.

Answer №2

The demonstration features a function known as omit(), which is designed to extract the keys from an object and remove specified ones before reconstructing the object based on the remaining keys.

Utilizing recursion, the omit() function iterates through all the values of the object associated with these remaining keys.

const data = {
    name: 'John',
    age: 30,
    details: {
        occupation: 'Engineer'
    }
};

const omit = ( obj, keys ) => obj.constructor.name === 'Object' && obj != null ? Object.keys(obj).filter(k => !keys.includes(k)).reduce((a, c) => ({
    ...a,
    [c]: omit( obj[c], keys )
}), {}) : obj;

console.log( omit(data, ['age']) );

console.log( omit(data, ['occupation']) );

console.log( omit(data, ['occupation','name']) );

console.log( omit(data, ['details']) );

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

Encountering a data retrieval issue when using the useSWR hook in a project using reactjs

I am trying to retrieve data from the backend using useSWR. However, I have encountered two bugs in the function getDataUseSWR. The errors occur at line 'fetch(url).then': 1: "Expected 0 arguments, but got 1."; 2: "Property 'then' does ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Assume we have two positive integers, N and X. In this scenario, N represents the total number of patients, while X denotes the time duration, measured in minutes, between the arrival

Suppose you are given two positive integers N and X. Here, N represents the total number of patients while X indicates the time duration (in minutes) after which a new patient will arrive. The doctor only provides 10 minutes to each patient for consultatio ...

The calender icon in Bootstrap4 datepicker input is unresponsive to clicks

template.html {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin= ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

What is the best way to pass a module from the controller to a Jade/Pug template and then use it as an argument in an event handler within the template?

I passed the module 'naija' to a template from the controller in this way: res.render('testing', {title:"filter setting page", nigeria:naija }); The func ...

"Encountered difficulty in retrieving the width of an element upon refreshing the

I have come across a puzzling situation with my code that involves determining the width of a block element. Here is an excerpt from the code snippet: //get the largest block: if no block, apply to first block var previous = $('.block-grid .block-gr ...

What is the best way to incorporate an "authorization" validation in certain NodeJs APIs?

In my project using react and node, I create all my react components in a dist/ directory. After uploading this directory to the server, I serve it through nodeJS using the express.static() method. server.use(express.static(__dirname + '/dist' ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Navigating through a complex array structure and having the capability to both search and filter its elements

hi there! I'm reaching out for some assistance with a challenge that I've encountered. Currently, I am working on developing a dashboard that iterates through criminal charges. I have structured the database table as follows: category charges ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

I am able to fill in the ServiceType field, but I am struggling to find the correct options for the ServiceName dropdown menu

Is there a way to dynamically update the ServiceName dropdown options based on the selected value in the ServiceType dropdown? $scope.ServiceTypeAndName = [ { "id":0, "type":"", "list":"" }, { "id":1, "ty ...

Tips for generating a <div> element with multiple children using a loop

section, I have configured a div element with a class named div class = "postWindow". When it comes to the HTML code, here is an example: <div class = "postWindow"> <div class = "userName">Initial Name</div> <div class = "p ...

Having trouble incorporating a Vue.js element onto a Blade template

I am currently experiencing an issue with loading a Vue.js component on my Blade engine. After adding the Vue.js component, it only loads either the Vue.js 'bootstrap' or the public/js/app.js file depending on what is commented out in the app.bla ...

What is the best way to divide the index.js file in a Node.js/Mean/Express project?

Currently, I have a single lengthy index.js route file within my node/mongo/express application. Here is how it's structured: app.js /models Schedule.js Task.js etc... /routes index.js /public /javascript etc... My goal is to ...

Is it feasible to activate a function when certain Vue data elements are altered?

Looking to monitor a set of data elements for changes and then save them in localStorage. Is there an easy way to achieve this? ...

Removing commas and non-numeric symbols from a string using JavaScript

Stripping both a comma and any non-numeric characters from a string can be a bit tricky, especially with RegExs involved :). Is there anyone who could provide assistance on how to achieve this? I need to remove commas, dashes, and anything that is not a ...

Encountering an issue when attempting to bring in a new library

When attempting to import a library, I encountered this error. https://i.sstatic.net/NYYQX.png The command used to obtain this library was: npm i queue Here is how I attempted to import it in my javascript: import Queue from "./node_modules/queue/ ...

"Unlocking the Potential: Maximizing the Benefits of the top.gg Vote Web

My bot has been verified on top.gg, and I'm looking to offer rewards to users who vote for my bot. How can I detect when someone votes for my bot, get their ID, check if it's the weekend, and take action after the vote? Essentially, how do I util ...