js数据类型转化问题?

下面这个data1怎转化成data2格式的?

let data1 = {1: "北京市", 3: "上海市", 7: "杭州市"}



let data2 = [{id:1,name:"北京市"},{id:3,name:"上海市"},{id:7,name:"杭州市"}]
阅读 2.3k
10 个回答
const data2 = Object.keys(data1).map(key => {
    return {
        id: Number(key),
        name: data1[key]
    };
});

image.png

  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))

image.png

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}))
推荐问题
logo
Microsoft
子站问答
访问
宣传栏