Hy, My Question is how we can map an array in react js in which the array has key-value pairs but these key values are dynamically added to the array . I mean I don't know what next key-value pair would come in an array.
example below
var array = [{ name: "kamran", age: 25 }, { dev: "kamran", hellow: "kamran" }, { "unknown key will be add dynamically": "unknown value to that key will be add dynamically" }];
for (var i = 0; i < array.length; i ) {
console.log(tifOptions[i]);
}
I want to show it on the table with keys and values using the map function. but the situation is data is coming from a rest API every time it gives me a different array of objects how could I show it will key and value I need to add to the project. because I don't know what key and value will come in the next API request
like below
first request from same API [ { 'name':"kamran", 'age':25, },
{
'dev':"js",
'db':"mongo",
},
];
second request from same API [ { 'name':"kamran", 'age':25, },
{
'dev':"js",
'db':"mongo",
},
{
'job':"student",
"salary":20000,
}
]; third request from same API [ { 'name':"kamran", 'age':25, },
{
'dev':"js",
'db':"mongo",
},
{
'job':"student",
"salary":20000,
},
{
' unknown key will be added':"unknown value will be added",
' unknown key will be added':"unknown value will be added",
}
];
and it goes on every time different key values how could I show this type of data on table with keys and value bcz I don't know in the next request what key value paire would come.
CodePudding user response:
I think the answer pretty obvious if you do some googling https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The function simply let you map a new array base on your base array no matter what element is in it
CodePudding user response:
From my understanding of your question, you are going to do something with the key & value pairs coming from the API.
var array = [{ name: "kamran", age: 25 }, { dev: "kamran", hellow: "kamran" }, { "unknown key will be add dynamically": "unknown value to that key will be add dynamically" }];
array.map(item => {
var keys = Object.keys(item);
var obj= {};
keys.forEach(key => {
console.log("key : " ,key, "value : ", item[key])
// do some logic here
obj[key] = item[key];
})
return obj;
}))}
Live link here : https://codesandbox.io/s/youthful-lewin-pgyu8u?file=/src/App.js