-1

I'm trying to add a specific item on the front of an array but I can't work out how to do this? I know you do it with unshift, but I'm not sure how to do it with a key value array?

var outgoingHeaders = {
    "send_client_version": 1,
    "send_auth_ticket": 5
};

function sendPacket(packetName, packetData) {
    const packetId = outgoingHeaders[packetName];
    const packetArray = {'packet_id' : packetId };
    // TODO: Add packetArray at the start of packetData
    socket.send(JSON.stringify(packetData));
}

Example of calling it...

sendPacket('send_auth_ticket', {
    'auth_ticket' : authTicket,
});
regu
  • 29
  • 3
  • 3
    Is `packetData` really an array? From what you wrote it seems like it's an object, and in that case you can't really control the order of the items. – klh Jan 19 '18 at 21:39
  • Not sure if this is the source of confusion but just in case: unlike some programming languages there is no "key value array" (or what some call an associative array) in Javascript. – luckyape Jan 19 '18 at 21:56
  • Not sure why you think its an object? – regu Jan 19 '18 at 21:57
  • 1
    Not sure why *you* think it's an array… – deceze Jan 19 '18 at 22:01
  • Because I pass an array to the function.. – regu Jan 19 '18 at 22:02
  • No you don't. `{}` is an *object*, `[]` is an array. – deceze Jan 19 '18 at 22:04
  • So I'm guess I'm asking how to do it with a key value object, I'm sorry if it was called something else but I usually call it a key value array, I apologize. – regu Jan 19 '18 at 22:05
  • Then "unshifting" and "order" are inappropriate too, since objects don't have an order. Do you merely want to add the key-value pair into the object…? – deceze Jan 19 '18 at 22:07
  • I just want to ensure that packet_id is the first item in the json string when sent to the server. – regu Jan 19 '18 at 22:08
  • 1
    And that ain't gonna happen. Objects. Have. No. Guaranteed. Order. Neither in Javascript nor JSON. – deceze Jan 19 '18 at 22:09

2 Answers2

0

You can use concat array method, like:

function sendPacket(packetName, packetData) {
  const packetId = outgoingHeaders[packetName];
  const packetArray = [{'packet_id' : packetId }];
  const data = packetArray.concat(packetData);
  socket.send(JSON.stringify(packetData));
}

Nice thing about this, you keep the immutability of your variables :)

0

Since you did not provided any JSON sample this is a suggestion:

var outgoingHeaders = {
  "nameee" : 33
}


function sendPacket(packetName, packetData) {
    var packetId = outgoingHeaders[packetName];
    var packetArray = {'packet_id' : packetId };
    // TODO: Add packetArray on the front of packetData
    packetData.unshift(packetArray);
    console.log(JSON.stringify(packetData, null, 4));
}




sendPacket("nameee", [{'packet_id' : 14 }, {'packet_id' : 5 }])
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313