Create new multidimensional Associative array from 2 arrays

前端 未结 3 1623
陌清茗
陌清茗 2021-01-15 12:15

I am looking for a solution to create a single multidimensional associate array in javascript.

What I have: I have a mysql database I am accessing with php and have

3条回答
  •  感情败类
    2021-01-15 12:58

    It's really unclear what you want, but there are a couple of serious flaws with your logic:

    1. var changes={}; ///this one way of declaring array in javascript

      No, it isn't. That's an Object, which is very different from an array.

    2. eval();

      You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.

    3. changes[key[value]]=value;

      This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...

      'a' => 1
      'b' => 2
      'c' => 3
      

      ... then changes will look like this after:

      1 => 'a'
      2 => 'b'
      3 => 'c'
      

      For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.

    4. Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.

    RE: Your clarification:

    This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.

    You want an array, where each key is the name of a property and each value is an array containing the old and new values.

    I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.

    var changes = {};
    var oldInfo = ;
    
    function change(key, value) {
      changes[key] = [ oldInfo[key], value ]  
    }
    

提交回复
热议问题