ES6将对象键值转换为单个对象的方法

时间:2018-09-29 18:07:10

标签: javascript arrays json ecmascript-6

我想将所有数据转换为一个对象,

let d = {
  "Coupon_Code": "code",
  "Coupon_Name": "namie",
  "Coupon_Desc": 1000,
  "selectedCity": [
    {
      "Coupon_City_Name": "xyz"
    }
  ],
  "selectedCategory": [
    {
      "Coupon_Category_Name": "Shopping"
    }
  ],
  "selectedCompany": [
    {
      "Coupon_Company_Name": "Shopper Stop"
    }
  ],
  "selectedState": [
    {
      "Coupon_State_Name": "abc"
    }
  ],
  "Coupon_Date": "2222-02-22",
}

我尝试了一些keysentries之类的Object方法,但是没有使用什么方法。 最终输出应为

let d = {
  Coupon_Code: "code",
  Coupon_Name: "namie",
  Coupon_Desc: 1000,
  Coupon_City_Name: "xyz",
  Coupon_Category_Name: "Shopping",
  Coupon_Company_Name: "Shopper Stop",
  Coupon_State_Name: "abc",
  Coupon_Date: "2222-02-22",
};

使用Venila Js和Es6获得上述结果的最佳和最佳方法是什么

5 个答案:

答案 0 :(得分:7)

Reduce原始对象的entries。如果条目的值是数组,则合并第一个元素;如果不合并,则合并原始键和值。您可以使用object spread将属性合并到对象中:

Child

答案 1 :(得分:2)

您可以使用Array.reduceObject.entries

Access-Control-Expose-Headers: allow

答案 2 :(得分:2)

您可以采用递归方法。

0 1
const
    fn = o => Object.assign(...Object.entries(o).map(([k, v]) => Array.isArray(v) ? Object.assign(...v.map(fn)) : { [k]: v })),
    d = { Coupon_Code: "code", Coupon_Name: "namie", Coupon_Desc: 1000, selectedCity: [{ Coupon_City_Name: "xyz" }], selectedCategory: [{ Coupon_Category_Name: "Shopping" }], selectedCompany: [{ Coupon_Company_Name: "Shopper Stop" }], selectedState: [{ Coupon_State_Name: "abc" }], Coupon_Date: "2222-02-22" },
    result = fn(d);

console.log(result);

答案 3 :(得分:1)

可能的迭代解决方案是:

function flatten(obj) {
    let r = {}
    for (let [key, value] of Object.entries(obj)) {
        if (Array.isArray(value)) {
            Object.assign(r, value[0]);
        } else {
            Object.assign(r, {[key]: value});
        }
    }
    return r;
}

答案 4 :(得分:0)

类似这样的东西:

const d = { Coupon_Code: "code", Coupon_Name: "namie", Coupon_Desc: 1000, selectedCity: [{ Coupon_City_Name: "xyz" }], selectedCategory: [{ Coupon_Category_Name: "Shopping" }], selectedCompany: [{ Coupon_Company_Name: "Shopper Stop" }], selectedState: [{ Coupon_State_Name: "abc" }], Coupon_Date: "2222-02-22" };

function toSingleObj(obj) {
    var result = {};
    Object.entries(obj).forEach(([key,value]) => {
        if (Array.isArray(value)) {
            Object.entries(value[0]).forEach(([k,v]) => {
                result[k] = v;
            });
        } else {
            result[key] = value;
        }
    });
    return result;    
}


console.log("Result: ", toSingleObj(d));