0

I am contracting an array to use it in react-native-searchable-dropdown'. I am trying to push my object into an array using the below code. i am facing issue. Please refer below.

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]);
  }

clone looks like below and clone is also converted into object(This is also a problem).

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'}"
]

what i am expecting:

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'}]

and clone should not be converted to object. SearchableDropdown accepts only array like [{id:1, name:'heat'}].

can anyone please suggest on how to achieve this?. i have tried different ways(like creating one object at a time and pushing into array, using object.assign, using [...clone, obj[0]] etc.,). i am not able to achieve what i am expecting.

3
  • 1
    How you got the obj object ? It is not a valid object Commented Jul 7, 2023 at 3:53
  • my initial object is like this [{"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"},{}] .. Then i converted into [{id:8,name:'Yyff'}...] in order to use it in Searchabledropdown. Searchabledropdown expects array like [{id:8,name:'Yyff'}..] Commented Jul 7, 2023 at 3:55
  • And, Searchabledropdown is not accepting objects. Commented Jul 7, 2023 at 4:08

1 Answer 1

0

If you want to push objects into an array without changing the array property and without converting the array to an object, change couple of lines like below,

let clone = [];
const 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' }
];

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

Try this and let me know , whether it works or not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.