K
K
Konstantin2022-03-02 17:29:30
PHP
Konstantin, 2022-03-02 17:29:30

How to pass an array as a variable to an object?

I want to shorten the entry, it works, but I just want to substitute a variable:

let arrOptions = [   
{ title: 'Домашний конфитюр', price: 'null' },
    { title: 'Изюм и орехи', price: 'null' },
    { title: 'Банан и шоколад', price: 'null' },
    { title: 'Яблоко и орехи', price: 'null' }
];

//создаем объект
 const newAttributes = {
            name: 'Дополнительно',
            visible: true,
            variation: true,
          };
//добавляем ключ и значение массив 

newAttributes.options = arrOptions;
newProduct.attributes = [newAttributes];

//работает корректно (консоль):
{
  name: 'Дополнительно',
  visible: true,
  variation: true,
  options: [
    { title: 'Домашний конфитюр', price: 'null' },
    { title: 'Изюм и орехи', price: 'null' },
    { title: 'Банан и шоколад', price: 'null' },
    { title: 'Яблоко и орехи', price: 'null' }
  ]
}


But if I try to make an entry like this instead of two extra lines:

const newAttributes = {
            name: 'Дополнительно',
            visible: true,
            variation: true,
            attributes: `${arrOptions}`,
          };

//то результат некорректный

{
  name: 'Дополнительно',
  visible: true,
  variation: true,
  attributes: '[object Object],[object Object],[object Object],[object Object]'
}


How correctly and briefly can you write - this attribute value?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2016-04-17
@alexey-m-ukolov

$_connect->exec('set names utf8');

$_connect_->exec

R
Rsa97, 2022-03-02
@gradk

const newAttributes = {
  name: 'Дополнительно',
  visible: true,
  variation: true,
  attributes: arrOptions,
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question