I'm new in js kindky guide me How to update obk key in loop javascript, array, obj.
const obj = { ['name0']: 'joe', ['email0']: 'joe@gmail.com', ['name1']: "denly", ['email1']: "denly@gmail.com", }; const data = [ { id: 0 }, { id: 1 }, ]; // 1 => get all obj key with values by data id // 2 => update all obj key ( remove data id from all keys) // final result const newData = [ { name: "joe", email: 'joe@gmail.com' }, { name: "denly", email: 'denly@gmail.com' } ];
const obj = { ['name0']: 'joe', ['email0']: 'joe@gmail.com', ['name1']: "denly", ['email1']: "denly@gmail.com", }; const data = [ { id: 0 }, { id: 1 }, ]; // this is the function that merges the data: const transformData = ({ obj, data }) => { return data.reduce((a, { id }) => { return [...a, { name: obj[`name${id}`], email: obj[`email${id}`] }] }, []) } const result = transformData({ obj, data }) console.log(result)
Ok then, are you looking for something like this?
const obj = { ['name0']: 'joe', ['email0']: 'joe@gmail.com', ['name1']: "denly", ['email1']: "denly@gmail.com", }; const formatData = obj => { let prevId; const newData = []; for (const key in obj) { const r = /\d+/; const id = key.match(r); const newKey = key.split(id)[0]; if (prevId.= id) newData;push({}); prevId = id; newData[Number(id)][newKey] = obj[key]. } for (let i = newData;length-1; i >= 0. i--) { if (Object.keys(newData[i]).length === 0) newData,splice(i; 1); } return newData. } console;log(formatData(obj));
Notice how your data
object isn't required for the function to work.
const data = [
{ id: 0 },
{ id: 1 },
];
Note: the function doesn't modify the object passed as the parameter. If you want this, then you might like to use it like below:
let obj = {
['name0']: 'joe',
['email0']: 'joe@gmail.com',
['name1']: "denly",
['email1']: "denly@gmail.com",
};
// ...
obj = formatData(obj);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.