js普通对象格式转换为json对象格式

有多个这样的对象

 {K: "NS11061", item_group: "A", brand_group: "1"}
 {K: "NS11061", item_group: "B", brand_group: "2"}

如何转换为

flag: "K",
code: "NS11061",
itemModifyImportBeanList: [
    {
        tagCode: "item_group",
        tagValue: "A"
    },
    {
        tagCode: "brand_group",
        tagValue: "1"
    }
]

flag: "K",
code: "NS11061",
itemModifyImportBeanList: [
    {
        tagCode: "item_group",
        tagValue: "B"
    },
    {
        tagCode: "brand_group",
        tagValue: "2"
    }
]

摸索了好久没找到合适的方法

阅读 2.9k
3 个回答

jsfiddle demo 链接:https://jsfiddle.net/liangxh/...

const obj = {K: "NS11061", item_group: "A", brand_group: "1"}
const newObj = {itemModifyImportBeanList: []}
Object.keys(obj).forEach(key => {
    const keyArr = ['K', 'S', 'M'];
    if (keyArr.includes(key}) {
        newObj['flag'] = key;
        newObj['code'] = obj[key];
      } else {
        newObj['itemModifyImportBeanList'].push({
          tagCode: key,
          tagValue: obj[key]
        })
      }
})
console.log(newObj)

找到规律用map做映射

//程序运行完成时一定要有输出语句,本工具才能正确展示运行结果。 
// 
const arr = [{K: "NS11061", item_group: "A", brand_group: "1"},
 {K: "NS11061", item_group: "B", brand_group: "2"}]

const aa = arr=>{
    return arr.map(item=>{
        const {K,M,S,...other}=item
        const obj = {}
        if(K){
            obj.flag = 'K'
            obj.code = item.K
        }
        if(M){
            obj.flag = 'M'
            obj.code = item.M
        }
        if(S){
            obj.flag = 'S'
            obj.code = item.S
        }
        obj.itemModifyImportBeanList = Object.keys(other).map(v=>({
            tagCode:v,
            tagValue:other[v]
        }))
        return obj
    })
}

 console.log(aa(arr))

用原生对象 JSON。需要这种格式,需要传缩进,即 json.stringify(obj, null, ' ')

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题