如何从对象键构建标签

how to build labels from the object key

我有一个模型 returns 像这样的对象:

{type:"Fiat", model:"500", color:"white"}
{type:"ford", model:"f250", color:"green"}

我需要根据对象键创建一个标签,例如类型、型号、颜色和 包含法币、500 等的列。 我试图使用:

model.map(elem=>{ Object.keys(elem)}

获取密钥,但我正在获取对象中每个项目的密钥。有什么方法可以获取key值吗?

Object.keys 给你钥匙。您可以使用键来获取值,例如 myObject[key]:

编辑:已更新以产生所需的输出:

const data = [
    {type:"Fiat", model:"500", color:"white"},
    {type:"ford", model:"f250", color:"green"}
]


const result = data.map(elem => {
    myKeys = Object.keys(elem)
    myResult = "";
    
    for (let x in myKeys) {
        myResult += "label" + (+x + 1) + "=" + myKeys[x] + ", ";
        // use elem[myKeys[x]] here to get the values (e.g. "Fiat", "500", "white")
    }
    return myResult;
})

console.log(result)

您可以使用

Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Object.keys()

The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

Array.prototype.reduce()

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

使用 map()Object.keys()reduce()

const car = [{type:"Fiat", model:"500", color:"white"},
    {type:"ford", model:"f250", color:"green"}]

var res = car.map(item => {
  return Object.keys(item).reduce((a, c, i) => {
    a[`label${i+1}`] = item[c]
    return a;
  }, {});
});

console.log(res);

或: for...in

The for...in statement iterates over all non-Symbol, enumerable properties of an object.

使用 map()Object.keys()for...in

const car = [{type:"Fiat", model:"500", color:"white"},
{type:"ford", model:"f250", color:"green"}]

var res = car.map(elem => { 
  var temp = {}, counter = 1;
  for(var k in elem){
    temp['label'+counter] = elem[k];
    counter++;
  }
  return temp;
});
console.log(res);

the output should be label1 = type, label2=model, label3 = color

如果你想用label+nth来命名

您可以映射您的汽车,然后通过遍历一个对象中的所有键来构造一个对象。

如果我有任何误解,请发表评论,我很乐意更改。 :)

const cars = [{
    type: "Fiat",
    model: "500",
    color: "white"
  },
  {
    type: "ford",
    model: "f250",
    color: "green"
  }
]


function getLabelsFromObject(model) {
  return Object.values(model).reduce(createLabelModel, {})
}

function createLabelModel(labels, label, i) {
  return Object.assign(labels, {[`label${i}`]: label})
}

console.log(cars.map(getLabelsFromObject))