js中如何获取键值并相互对应?

How can I get key values and correspond it to each other in js?

我有一个对象数组如下:

[
    {
        "card_key": "Edition",
        "card_value": "Elite Fight Night"
    },
    {
        "card_key": "Card ID",
        "card_value": "15824885587"
    }
]

我想要如下输出:

{
  "Edition":"Elite Fight Night",
  "Card ID":"15824885587"
}

如何在 javaScript 中执行此操作?我是 js 的初学者。不知道我该怎么做

只需遍历数组并将 card_key 的值保存为键,将 card_value 的值保存为新对象的值。

如下图

    
obj_array = [
    
    {
        "card_key": "Edition",
        "card_value": "Elite Fight Night"
    },
    {
        "card_key": "Card ID",
        "card_value": "15824885587"
    }
    ]

objs1 = {}

for (const x of obj_array)

    objs1[x["card_key"]] = x["card_value"]

console.log(objs1)
    

let arr = [
{
    "card_key": "Edition",
    "card_value": "Elite Fight Night"
},
{
    "card_key": "Card ID",
    "card_value": "15824885587"
}
];
let finalObj = {};
for(let i = 0; i < arr.length; i++) {
    let obj = arr[i];
    finalObj[obj['card_key']] = obj['card_value'];
}
console.log(finalObj);

如果数据具有您提供的结构,您可以使用此代码:

const input = [
    {
        "card_key": "Edition",
        "card_value": "Elite Fight Night"
    },
    {
        "card_key": "Card ID",
        "card_value": "15824885587"
    }
];
const expectedData = input.reduce((acc, item) => ({...acc, [item.card_key]: item.card_value}), {});
console.log(expectedData);

这是允许使用动态对象键的括号表示法。

链接:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

https://javascript.info/object

Reduce 是一个函数,允许根据输入数组计算值。您可以在此处阅读有关 reduce 的信息:

https://javascript.info/array-methods#reduce-reduceright

还有关于扩展运算符 (...):

https://javascript.info/rest-parameters-spread#spread-syntax

您可以使用 mapObject.fromEntries

const data = [
    {
        "card_key": "Edition",
        "card_value": "Elite Fight Night"
    },
    {
        "card_key": "Card ID",
        "card_value": "15824885587"
    }
]

const result = Object.fromEntries(data.map(d => [d.card_key, d.card_value]))

console.log(result)

const data = [{
    "card_key": "Edition",
    "card_value": "Elite Fight Night"
  },
  {
    "card_key": "Card ID",
    "card_value": "15824885587"
  }
]

console.log(data.reduce((a, c) => {
  a[c.card_key] = c.card_value;
  return a
}, {}))