how can you add an object to an array in react native without altering the properties of the array

In my attempt to contract an array for use in 'react-native-searchable-dropdown', I have encountered an issue while trying to push objects into the array. Here is the code snippet that I am struggling with:

let clone=[];
obj={{id:8,name:'Yyff'},{id:8,name:'Yyff'},{id:7,name:'Hsjdb56'},{id:6,name:'Suku'},{id:5,name:'Jira'},{id:4,name:'Suku '},{id:3,name:'Joseph'},{id:2,name:'Rosh'},{id:1,name:'Zulu'}}

let arr=Object.keys(obj);
for (var j = 0; j < obj.length; j++){
    clone.push(obj[arr[j]);
  }

The resulting 'clone' array appears as follows and has also been converted into an object (which is not desired):

Array [
  "{id:8,name:'Yyff'}",
  "{id:7,name:'Hsjdb56'}",
  "{id:6,name:'Suku'}",
  "{id:5,name:'Jira'}",
  "{id:4,name:'Suku '}",
  "{id:3,name:'Joseph'}",
  "{id:2,name:'Rosh'}",
  "{id:1,name:'Zulu'}"
]

Expected result:

clone=[{id:8,name:'Yyff'},{id:8,name:'Yyff'},{id:7,name:'Hsjdb56'},{id:6,name:'Suku'},{id:5,name:'Jira'},{id:4,name:'Suku '},{id:3,name:'Joseph'},{id:2,name:'Rosh'},{id:1,name:'Zulu'}]

Furthermore, the 'clone' should not be converted to an object since SearchableDropdown only accepts arrays like [{id:1, name:'heat'}].

If anyone could offer suggestions on how to achieve this, it would be greatly appreciated. I have tried various methods but haven't been able to obtain the desired outcome.

Answer №1

To store new elements in an array without altering the original array or converting it to an object, you can modify a couple of lines as shown below:

let copy = [];
const data = [
  { id: 8, name: 'Yyff' },
  { id: 8, name: 'Yyff' },
  { id: 7, name: 'Hsjdb56' },
  { id: 6, name: 'Suku' },
  { id: 5, name: 'Jira' },
  { id: 4, name: 'Suku ' },
  { id: 3, name: 'Joseph' },
  { id: 2, name: 'Rosh' },
  { id: 1, name: 'Zulu' }
];

for (let k = 0; k < data.length; k++) {
  copy.push({ ...data[k] });
}

Give this a try and let me know if it solves your problem.

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

Utilize Jackson to properly deserialize JSON and ensure the correct subclass type is assigned

Resolve string into object structure .. ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); System.out.println(json); // Here is the output Status status = new ObjectMapper().re ...

Guide on passing variables in a Flutter http.get request

I have been researching Flutter documentation on making http.get requests to retrieve data from a database. However, I only want to fetch specific data by passing a variable in my method. How can I pass this variable 'a' to the server in the foll ...

Organize subarrays within an array in Mongoose

I am dealing with mongoDb data that looks like this: [{ "_id": { "$oid": "57c6699711bd6a0976cabe8a" }, "ID": "1111", "FullName": "AAA", "Category": [ { "CategoryId": { "$oid": "57c66ebedcba0f63c1ceea51" }, "_id" ...

Incorporate the Vue JS response into the table component

I am attempting to append my response from Vue into a table but I am unable to do so and I don't know why. I can retrieve all the data from my database, I can see it in my web browser console, but my table remains empty. Below is my current code: Vu ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

Warning: ComponentMounts has been renamed. Proceed with caution

I'm encountering a persistent warning in my application and I'm struggling to resolve it. Despite running npx react-codemod rename-unsafe-lifecycles as suggested, the error persists and troubleshooting is proving to be challenging. The specific w ...

Implementing asynchronous code when updating state using React hooks

Here's a scenario I'm dealing with: const [loading, setLoading] = useState(false); ... setLoading(true); doSomething(); // <--- at this point, loading remains false. Since setting state is asynchronous, what would be the best approach to ...

Exploring the functionality of generic components in React Native when using TypeScript

As an illustration, consider export class FlatList<ItemT> extends React.Component<FlatListProps<ItemT>> which incorporates the generic type ItemT. How can I utilize it in a .tsx code? When not parametrized, it appears like this: <Flat ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

Unable to redirect Firebase Hosting root to a Cloud Function successfully

Currently I am utilizing Firebase Hosting along with a Firebase.json file that is configured to direct all traffic towards a cloud function (prerender) responsible for populating meta and og tags for SEO purposes. { "hosting": { "public": "dist/pr ...

What steps do I need to take to ensure that my AJAX button press request functions properly within my Django setup?

Is there a way to utilize a JavaScript string variable in a Python function and then return it back to a JavaScript variable efficiently? Perhaps using Json/ajax can help with this? To start, there is an HTML element where a string is stored: <h2 id=&q ...

Creating JavaScript Powered Pie Charts

I am seeking a lightweight JavaScript pie chart option to replace PlotKit, as the library is too large for my low bandwidth. Ideally, I am looking for a compact and efficient solution in either JavaScript or jQuery. ...

Rails offers a unique hybrid approach that falls between Ember and traditional JavaScript responses

My current project is a standard rails application that has primarily utilized HTML without any AJAX. However, I am planning to gradually incorporate "remote" links and support for JS responses to improve the user experience. While I acknowledge that gener ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Only send the parameter for variables that are not empty in the AJAX data

How can I pass the variables that are not empty in the data object for an AJAX request? In this scenario, the area variable is empty so I need to pass parameters for city and listing type instead. Can someone please help me figure out how to do this? va ...

Trigger a notification from one webpage to another (PHP, JavaScript, HTML)

I'm currently working on a website that consists of both a receptionist page and a user page with multiple logins. The receptionist page displays a table listing all logged-in users, including their status (either ready or busy). This table is refresh ...

Obtaining the sum of two variables from two separate functions results in a value of NaN

Why is it that I'm seeing a NaN result when trying to access a variable in two different functions? This is my code var n_standard = 0; var n_quad = 0; var totalQuad; var totalStandard; var total = totalStandard + totalQuad; ...

What are the best ways to handle JSON data in Python and Bash?

Having trouble parsing the JSON data below using Bash and Python. Errors are popping up. I am trying to extract the name and ObjectID information from the JSON and store it in an array, but I'm not sure how to accomplish this. Sample JSON: { ...