简体   繁体   English

JSON 对象展平或使用 javascript 创建

[英]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.我想使用 javascript 实现上述对象。

Thank you !谢谢 !

You can try using map() and Object.assign() like the following way:您可以尝试使用map()Object.assign() ,如下所示:

 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 .您可以使用Array.reduceComputed 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 .您可以将每个对象的值映射到条目,然后使用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; }

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

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