当javascript中的键相同时,如何从对象获取数据并创建数组?

时间:2021-04-07 09:00:56

标签: javascript arrays javascript-objects

这是我正在谈论的场景:

let obj = {
      id: "kjhgfr^&*()(*UY",
      id: "kjhgfr^OIJHB",
      id: "kjhgfr^)(*&^%Y",
      id: "DFGHI(*&YTRDTYHKI*",
      id: ")(IUHGVYUJKO))(*UY",
      id: "VGYUKO(*UYH",
      id: "BHYUIOP)(*&^T%",
      id: "0987654567890",
      id: "5678909876543",
    };

我想用这样的 id 创建一个数组。

[
  "5678909876543",
  "0987654567890",
  "VGYUKO(*UYH",
  "kjhgfr^&*()(*UY",
  "VGYUKO(*UYH",
];

2 个答案:

答案 0 :(得分:2)

您的对象不正确。

可能与: Javascript object literal - possible to add duplicate keys?

因此,它将被覆盖以获取最后一个值。

let obj ={id:"kjhgfr^&*()(*UY",id:"kjhgfr^OIJHB",id:"kjhgfr^)(*&^%Y",id:"DFGHI(*&YTRDTYHKI*",id:")(IUHGVYUJKO))(*UY",id:"VGYUKO(*UYH",id:"BHYUIOP)(*&^T%",id:"0987654567890",id:"5678909876543",};

console.log(obj);
// { "id": "5678909876543"}

答案 1 :(得分:-1)

您不能有重复的密钥。每个相同的键都会覆盖之前定义的值。

你可以试试这个(假设你可以控制输入):

#include <iostream>
#include <string>
using namespace std;



int main() {
  string ride;
  int age, tp, sp;
  double td;

  //print outs and input
  cout<<"What ride would you like to buy a ticket for? "<<endl;
  cin>>ride;
  
  cout<<"How old are you?"<<endl;
  cin>>age;

这类似于以下问题:Read and loop through an object with non-unique key value pairs