简体   繁体   中英

JSON object flattening or creation with javascript

Object:

{
    firstName: "Doe",
    address: "California",
    mobile: "xxxx"
}

List of objects or Array:

[
  { name: "course1", value: "1" } ,
  { name: "course2", value: "2" } ,
  { name: "course3", value: "3" }
]

Expected output or object from:

{
  firstName: "Doe",
  address: "California",
  mobile: "xxxx",
  course1: "1",
  course2: "2",
  course3: "3"
}

I want to achieve above object using javascript.

Thank you !

You can try using map() and Object.assign() like the following way:

 var obj = { firstName : "Doe", address : "California", mobile : "xxxx" }; var arr = [{name : "course1",value : "1"} , {name : "course2",value : "2"} , {name : "course3",value : "3"}]; arr = arr.map(v => ({[v.name]: v.value})); var newObj = Object.assign(obj, Object.assign({}, ...arr)); console.log(newObj);

You can achieve the expected output using Array.reduce and Computed property names .

 let data = { firstName : "Doe", address : "California", mobile : "xxxx" }; let courses = [{name : "course1",value : "1"} , {name : "course2",value : "2"} , {name : "course3",value : "3"}]; const finalRes = courses.reduce((res, obj) => { return { ...res, [obj.name]: obj.value }; }, {...data}); console.log(finalRes)

You can map the values of each object to entries and then turn those into an object using Object.fromEntries . After you have that new object, apply it to the original.

 const sourceObject = { firstName: "Doe", address: "California", mobile: "xxxx" }; const propArray = [ { name: "course1", value: "1" } , { name: "course2", value: "2" } , { name: "course3", value: "3" } ]; const resultObject = { ...sourceObject, ...Object.fromEntries(propArray.map(p => Object.values(p))) }; console.log(resultObject);
 .as-console-wrapper { top: 0; max-height: 100% !important; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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