下面这个data1怎转化成data2格式的?
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}
let data2 = [{id:1,name:"北京市"},{id:3,name:"上海市"},{id:7,name:"杭州市"}]
下面这个data1怎转化成data2格式的?
let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}
let data2 = [{id:1,name:"北京市"},{id:3,name:"上海市"},{id:7,name:"杭州市"}]
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)
6 回答3k 阅读✓ 已解决
8 回答4.8k 阅读✓ 已解决
6 回答3.5k 阅读✓ 已解决
5 回答2.9k 阅读✓ 已解决
6 回答2.4k 阅读
5 回答6.4k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决