A
A
Anastasia2021-06-08 23:13:47
JavaScript
Anastasia, 2021-06-08 23:13:47

How to set a key in an array (object) as a variable?

Hello. This is how PHP works. I need to do the same in JS:

$id = 'АЙДИ';
$key1 = 'ВНУТРЕННИЙ КЛЮЧ 1';
$key2 = 'ВНУТРЕННИЙ КЛЮЧ 2';
$val1 = 'ЗНАЧЕНИЕ1';
$val2 = 'ЗНАЧЕНИЕ2';

$id2 = 'АЙДИ2';
$key3 = 'ВНУТРЕННИЙ КЛЮЧ 3';
$key4 = 'ВНУТРЕННИЙ КЛЮЧ 4';
$val3 = 'ЗНАЧЕНИЕ3';
$val4 = 'ЗНАЧЕНИЕ4';

$array = [];

$array[$id][$key1] = $val1;
$array[$id][$key2] = $val2;
$array[$id2][$key3] = $val3;
$array[$id2][$key4] = $val4;

echo json_encode($array);

Here is the result:
60bfceff9c005313651101.jpeg

It is important that you can then do this:
$array[$id][$key1] = $val4;
and the data would be overwritten, and not a new record would be created

Here is the original JS
let id = 'АЙДИ';
let key1 = 'ВНУТРЕННИЙ КЛЮЧ 1';
let key2 = 'ВНУТРЕННИЙ КЛЮЧ 2';
let val1 = 'ЗНАЧЕНИЕ1';
let val2 = 'ЗНАЧЕНИЕ2';

let id2 = 'АЙДИ2';
let key3 = 'ВНУТРЕННИЙ КЛЮЧ 3';
let key4 = 'ВНУТРЕННИЙ КЛЮЧ 4';
let val3 = 'ЗНАЧЕНИЕ3';
let val4 = 'ЗНАЧЕНИЕ4';

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill, 2021-06-09
@nastya97core

const obj = {};

obj[id] = {};
obj[id][key1] = val1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question