js数据类型转化问题?
下面这个data1怎转化成data2格式的?
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}let data2 = [{id:1,name:"北京市"},{id:3,name:"上海市"},{id:7,name:"杭州市"}]
回答:
const data2 = Object.keys(data1).map(key => { return {
id: Number(key),
name: data1[key]
};
});
回答:
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"} let data2 = []
for(const key in data1) {
data2.push({
id: Number(key),
name: data1[key]
})
}
// 排序
data2.sort(() => 1)
console.log(data2);
回答:
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}
let data2 = []
for (const [id, name] of Object.entries(data1)) {
data2.push({ id, name })
}
回答:
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}function convertData (obj) {
const result = []
for(let key in obj) {
result.push({
id: Number(key),
name: obj[key]
})
}
result.sort(function (a, b) {
return a.id - b.id
})
return result
}
console.log(convertData(data1))
回答:
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}Object.entries(data1).map(([id,name])=>{
return {id,name}
})
回答:
let citiesDict = {1: "北京市", 3: "上海市", 7: "杭州市"};let citiesList = [];
for (let key in citiesDict) {
if (citiesDict.hasOwnProperty(key)) {
citiesList.push({id: parseInt(key), name: citiesDict[key]});
}
}
console.log(citiesList);
回答:
function transform(obj) { var ret = [];
for (var key in obj) {
ret.push({ id: +key, name: obj[key] });
}
return ret;
}
console.log(transform(data1));
回答:
// 第一种:let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}
let arr = [],obj = {}
for (let item in data1) {
obj = {
id: item,
name: data1[item]
}
arr.push(obj)
}
console.log(arr)
// 第二种
let brr = Object.entries(data1).map(([id,name]) => ({
id,
name
}))
console.log(brr)
回答:
let data = Object.entries(data1).map(item => { return {
id: item[0],
name: item[1]
}
})
console.log(data)
回答:
Object.entries(data1).map(([id,name])=>({id,name}))
以上是 js数据类型转化问题? 的全部内容, 来源链接: utcz.com/p/934142.html