简体   繁体   English

如何将javascript变量组合成一个对象

[英]How do I combine javascript variables into a object

I need to combine all variables in one object:我需要将所有变量组合在一个对象中:

$.get("https://www.virginmegastore.ae/en/gaming/playstation/playstation-games/sonic-forces---ps4/p/714792", function (data) {
    var productNamePost=$("[name='productNamePost']").val();
    var productCodePost=$("[name='productCodePost']").val();
    var bg = $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image');
    var productPrice=$(".price__container > .price__value > .price__number").text();
    var url      = window.location.href;   

    console.log(url);
});

Sorry the question was unclear,i was need this对不起,问题不清楚,我需要这个

let obj = Object.assign({},var)

I also need to run the code when the button clicked我还需要在单击按钮时运行代码

 $.get("https://www.virginmegastore.ae/en/gaming/playstation/playstation-games/sonic-forces---ps4/p/714792", function (data) {    
 $("#addToCartForm > #addToCartButton").click(function(){ 
         var productNamePost=$("[name='productNamePost']").val();
         var productCodePost=$("[name='productCodePost']").val();
         var bg = $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image');
         var productPrice=$(".price__container > .price__value > .price__number").text();
         var url      = window.location.href;   
        let obj = Object.assign({}, [productNamePost, productCodePost, bg, productPrice, url]);
        console.log(obj)});

});

but i got below error when i clicked the button:但是当我单击按钮时出现以下错误:

在此处输入图片说明

Try this:尝试这个:

let obj = Object.assign({}, [
   productNamePost: $("[name='productNamePost']").val(), 
   productCodePost: $("[name='productCodePost']").val(), 
   bg: $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image'), 
   productPrice: $(".price__container > .price__value > .price__number").text(), 
   url: window.location.href
]);

This will create an object array with all your variables.这将创建一个包含所有变量的对象数组。 Read more about Object.assign() here 在此处阅读有关Object.assign()更多信息

And what's the problem?有什么问题?

const object = {
  productNamePost: $("[name='productNamePost']").val(),
  productCodePost: $("[name='productCodePost']").val(),
  bg: $('.pdp_image-carousel-image.js-zoomImage-mobile').css('background-image'),
  productPrice: $(".price__container > .price__value > .price__number").text(),
  url: window.location.href,
}

console.log(object.url); // and use

Run to read .运行阅读

Like this?像这样?

var newObj = {
  "productNamePost": $("[name='productNamePost']").val(),
  "productCodePost": $("[name='productCodePost']").val(),
  "variable_name": variable_value
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM