通过位置从2d数组中获取2个值

时间:2019-07-09 07:01:31

标签: javascript php asp.net arrays

我需要按位置从此数组顺序中获取2个值

var sosmed = [
  "Twitter",
  "Facebook"
][
  "rey",
  "ray lard"
];

我如何获得像"twitter = rey" , "Facebook = rey lard"

这样的价值
  • Twitter =雷伊
  • Facebook =雷伊猪油

3 个答案:

答案 0 :(得分:0)

我使用splat(...)运算符对数组进行转置,然后将其转换为每个子数组的键值对

 public List<Lookup> search(String filter) {
        return (List<Lookup>) entityManager.createNativeQuery(
                "select * from farm.lookup where data @>'{\"details\":{\"state\": [\"solid\",\"liquid\"]}}' or name ='pesticide' or name = 'fertilizer'",
                Lookup.class).getResultList();
    }

Working demo

JavaScript版本,

$arr = [
    [
        "Twitter",
        "Facebook",
    ], [
        "rey",
        "ray lard",
    ],
];
$arr = array_map(function($item){ return [$item[0] => $item[1]];},array_map(null, ...$arr));
echo json_encode($arr);

输出

<script type="text/javascript">
var temp = [
    [
        "Twitter",
        "Facebook",
    ], [
        "rey",
        "ray lard",
    ],
];
temp = temp[0].map((col, i) => temp.map(row => row[i]));
result = [];

for(i in temp){
    if(!result[i]){
        result[i] = [];
    }
    result[i][temp[i][0]] = temp[i][1];
}
console.log(result);
</script>

答案 1 :(得分:0)

对于这样的2D阵列

var array = [[
  "Twitter",
  "Facebook"
],[
  "rey",
  "ray lard"
]];

解决方案:在VanillaJS中

let obj = {};
array[0].forEach((item,index) => {
obj[item] = array[1][index] || '';
})

使用Lodash:

_.zipObject(array[0], array[1]);

输出:

{Twitter: "rey", Facebook: "ray lard"}

答案 2 :(得分:0)

您的数组声明中有错误。首先解决该问题。

var sosmed = [[
  "Twitter",
  "Facebook"
],[
  "rey",
  "ray lard"
]];

此后,您可以通过在主数组内的第一个子数组上执行map操作并为每个子数组创建适当的对象来获得所需的结果。

const result = sosmed[0].map((company, i) => {
  const obj = new Object();
  obj[company] = sosmed[1][i];
  return obj;
});