對不起,如果標題很亂,我不知道如何正確表達,但它會更容易顯示。
我正在使用 React JS,并且從我的資料庫中獲取此物件:
{
id1: "1",
name1: "Jon",
image1: {url: "...."},
id2: "2",
name2: "Ron",
image2: {url: "...." , height: "10"},
id3: "2",
name3: "Jess",
image3: {url: "...." , height: "10"},
...
}
依此類推,物件中的所有欄位都是獨立的,但我需要它是一個陣列(或物件,我可以通過 Object.keys 映射它..)和每 3 個欄位(名稱、ID、影像)將在同一個物件中,因此我可以將其映射為與我的組件一起使用,
這是我正在努力制作的示例輸出:
[
{ name1:"Jon", id1:"1", image1: { url:"....", height:"10" } },
{ name2:"Ron", id2:"2", image2: { url:"....", height:"10" } },
{ name3:"Jess", id3:"3", image3: { url:"....", height:"10" } },
]
提前感謝您的幫助!
uj5u.com熱心網友回復:
我讓你一段代碼誰做了那個轉變
import React from 'react';
function Question24() {
const initialObject = {
id1: "1",
name1: "Jon",
image1: {url: "...."},
id2: "2",
name2: "Ron",
image2: {url: "...." , height: "10"},
id3: "2",
name3: "Jess",
image3: {url: "...." , height: "10"},
};
const result = [];
let index = 1;
while(Object.keys(initialObject).length) {
const idKey = `id${index}`;
const nameKey = `name${index}`;
const imageKey = `image${index}`;
const resObject = {};
// I whould do -> resObject.id = initialObject[idKey];
resObject[idKey] = initialObject[idKey];
delete initialObject[idKey];
// I whould do -> resObject.name = initialObject[idKey];
resObject[nameKey] = initialObject[nameKey];
delete initialObject[nameKey];
// I whould do -> resObject.image = initialObject[idKey];
resObject[imageKey] = initialObject[imageKey];
delete initialObject[imageKey];
result.push(resObject);
index ;
}
console.log("result: ", result);
return (
<div>Check the console</div>
);
}
export default Question24;
我希望我對你有所幫助:)
uj5u.com熱心網友回復:
這很簡單,只需遍歷物件鍵并每第三步計數一次,然后將最后 3 個條目放入答案陣列中。盡管我不確定該模型是否是從資料庫獲取資料的最佳實踐。
obj = {
id1: "1",
name1: "Jon",
image1: {url: "...."},
id2: "2",
name2: "Ron",
image2: {url: "...." , height: "10"},
id3: "2",
name3: "Jess",
}
let answer = []
let temp = {}
let counter = 1;
for (let item in obj) {
temp[item] = obj[item]
if(counter == 3)
{
answer.push(temp);
temp = {}
counter = 1;
continue;
}
counter ;
}
// in case number of keys is not dividable by 3 and temp is not empty
answer.push(temp);
uj5u.com熱心網友回復:
你可以試試這段代碼:
let object = {
id1: "1",
name1: "Jon",
image1: {url: "...."},
id2: "2",
name2: "Ron",
image2: {url: "...." , height: "10"},
id3: "2",
name3: "Jess",
image3: {url: "...." , height: "10"},
};
const convertToArr = (object) => {
let arr = [];
for(let i=1; i<=Object.keys(object).length / 3; i ){
let obj = {};
obj.id = object[`id${i}`];
obj.name = object[`name${i}`];
obj.image = object[`image${i}`];
arr.push(obj);
}
return arr;
}
console.log(convertToArr(object));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/479274.html
標籤:javascript 数组 反应 目的
下一篇:如何使陣列的嵌套項成為物件?
