Tengo datos json y quiero manipularlos y almacenarlos en el estado setNewdata
const [newdata, setNewdata] = useState([]) const data = [{ id: 2048, title: 'フューチャーワークス', account_title_id: 1, detailed_id: 1, currency_id: 2, }, { id: 2056, title: 'ああああああ', account_title_id: 1, detailed_id: 2, currency_id: 2, }, ] quiero procesar este json para agregar dos claves, hay una label y un value en reaccionar
[{ id: 2048, title: 'フューチャーワークス', account_title_id: 1, detailed_id: 1, currency_id: 2, label: 'フューチャーワークス - 2048', // combine from id and title value: '1 - 1 - 2', // combine from account_title_id,detailed_id }, { id: 2056, title: 'ああああああ', account_title_id: 1, detailed_id: 2, currency_id: 2, label: 'ああああああ - 2048', // combine from id and title value: '1 - 2 - 2', // combine from account_title_id,detailed_id,currency_id }, ] data.forEach((current) => { ,.... })Puede hacer uso del map aquí y devolverá una nueva matriz y establecerá los datos como:
setNewData(result); const data = [ { id: 2048, title: "フューチャーワークス", account_title_id: 1, detailed_id: 1, currency_id: 2, }, { id: 2056, title: "ああああああ", account_title_id: 1, detailed_id: 2, currency_id: 2, }, ]; const result = data.map((o) => ({ ...o, label: `${o.title} - ${o.id}`, value: `${o.account_title_id} - ${o.detailed_id} - ${o.currency_id}`, })); // setNewData(result); console.log(result);map sobre la matriz para producir una nueva matriz de objetos.
Para cada objeto, desestructuraría las propiedades y luego las juntaría en un nuevo objeto con las nuevas propiedades de etiqueta y valor.
Actualice el estado con la matriz devuelta.
const data=[{id:2048,title:"フューチャーワークス",account_title_id:1,detailed_id:1,currency_id:2},{id:2056,title:"ああああああ",account_title_id:1,detailed_id:2,currency_id:2}]; const out = data.map(obj => { const { id, title, account_title_id, detailed_id, currency_id } = obj; return { id, title, account_title_id, detailed_id, currency_id, label: `${title} - ${id}`, value: `${account_title_id} - ${detailed_id} - ${currency_id}` }; }); console.log(out);aquí un foreach sobre datos para implementar nuevas propiedades en su Array
data.forEach(element => { element.label = element.title + " - " + element.id element.value = element.account_title_id + " - " + element.detailed_id + " - " + element.currency_id })