Extract the initial 7 keys from an object and transfer them to a separate object

Is there a way in JavaScript to create a new object that contains only the first 7 keys of another object? This is the object structure from which I want to extract the data.

{"data":[{"id":2338785,"team1":{"id":10531,"name":"Just For Fun"},"team2":{"id":10017,"name":"Rugratz"},"result":"2 - 0","event":{"name":"Mythic Cup 5","id":5148},"format":"bo3","stars":0,"date":1578279271000},....],"last_update":1578329378792}

Assuming there are 100 keys like this one, how can I specifically copy only the first 7 keys into a new object using JavaScript?

Answer №1

Technically speaking, the given Object only contains 2 keys. However, if you are referring to the data object, there is a solution available.

const MyNewObject = Object.entries(YourObject)
const results = []

Using a simple for loop:

MyNewObject.forEach((pair,i) => {
    // It breaks for the 8th item and does not push it to the results array
    if (i === 7) break;
    results.push(pair)
}

Alternatively, you can use slice:

// A cleaner solution, you can eliminate the empty results array above
const thisNewResult = MyNewObject.slice(0,6)

Finally, the results are an array of key value pairs. You can create a new object from these result entries with the following code:

const finalResults = Object.fromEntries(results)

It is important to note that the order may not be as expected, as Object.Entries follows the same order as a for-in loop. For more information, visit Elements order in a "for (… in …)" loop.

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

``Can you please explain how one can retrieve data from a website using a script

I am looking to develop a script that can track prices on a travel website. I don't have any issues with extracting the data from a file ... but I'm unsure how to automate retrieving the entire site with that information. Here is the command I ...

Tips for creating multiple popups using a single line of JavaScript code

I am new to JavaScript and I am attempting to create a popup. However, I am facing an issue in opening two divs with a single line of JavaScript code. Only one div opens while the other remains closed despite trying various solutions found on this website. ...

Convert JSON information into an array and map it in Swift

I am currently facing a certain challenge. My approach involves using Alamofire request to retrieve a JSON response. Alamofire.request(url, method: .get).responseJSON { response in if response.result.isSuccess { print ...

Combine the click event and onkeydown event within a single function

I have a function that sends a message when the Enter key is pressed. However, I also created a button to send a message, but when I call this function, the message doesn't send, even though I added a click event. function inputKeyDown(event, input ...

Serializing objects into JSON format using a standard encoder

When it comes to JSON-serializing custom non-serializable objects, the traditional approach involves subclassing json.JSONEncoder and then supplying a custom encoder to json.dumps(). Typically, this process looks something like this: class CustomEncoder(j ...

Using setTimeout() in JavaScript to create a delay between functions

Is there a way to add a delay between the execution of each function in my program? Currently, I have the following setup: function function0() { setTimeout(function1, 3000); setTimeout(function2, 3000); setTimeout(function0, 3000); } While t ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

AngularJS default ngOptions for parent and child models

Is there a way to set default ngOptions through parent/child models? Here, the OP demonstrates using ngOptions with parent/child relationships. template <select ng-model="x.site" ng-options="s.site for s in data"></select> <select ng-mode ...

Json file shared globally across multiple projects within a single asp.net core 2.0 solution

I have created a project structure with multiple components: Yupii.Games -> Class Library for sharing settings and utilities Yupii.Games.Web -> Web application Yupii.Games.Api -> Web API The database I am using is mongoDB, and I want to adhere ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Determine the total number of possible paths in a two-dimensional binary matrix (C programming language)

During a recent interview, I was faced with the following problem in C and have been struggling to come up with an elegant solution: You are given a two-dimensional array with M rows and N columns. Your starting position is (0,0) at the top-left cell of ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

The Axios interceptor is failing to retrieve the user's current authentication token from the Vuex store

Currently, I am utilizing Axios to transmit user input to a DRF API, which then returns an authentication token. This token is being saved in the Vuex store. However, when I attempt to request another API endpoint using Axios with the most recent token in ...

Issue with the select element in Material UI v1

I could really use some assistance =) Currently, I'm utilizing Material UI V1 beta to populate data into a DropDown menu. The WS (Web Service) I have implemented seems to be functioning correctly as I can see the first option from my Web Service in t ...

Error detected in JSON parsing

I keep encountering a json parse error Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 2.) This indicates that there is an issue in the jSON response. What's stra ...

Halting Execution After Placing an Object in Three.js Scene with Javascript

It seems like a simple task, but I've been struggling with it for days. How can I add objects to a scene with a pause between each addition? Inside a loop{ I call the make_obj function() then I call the wait function() } The issue is that the pr ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...