简体   繁体   English

映射数组内的对象

[英]mapping objects inside an array

I'm trying to create an object with these two a and b, first one's header columns are corresponding to another object's keys.我正在尝试使用这两个 a 和 b 创建一个对象,第一个的标题列对应于另一个对象的键。 For Example:例如:

a =[{  name: 'CreatedDateTime', header: 'Tarih' },
    {  name: 'Name', header: 'Adi' }]

b= [{ CreatedDateTime:"10.1.2021" },{Name:"Merve"}]

The output should be like this:输出应该是这样的:

c=[{Tarih:"10.1.2021" , Adi:"Merve" }]

How can i do that?我怎样才能做到这一点?

You can reduce the a array to the object you want by您可以将a数组减少为您想要的对象

  1. Iterating each entry and extracting the name and header properties迭代每个条目并提取nameheader属性
  2. Using the header as the object key使用header作为对象键
  3. Using the matching index from b (if it exists) and extracting the name property as the value使用b中的匹配索引(如果存在)并提取name属性作为值

 const a = [{"name":"CreatedDateTime","header":"Tarih"},{"name":"Name","header":"Adi"}] const b = [{"CreatedDateTime":"10.1.2021"},{"Name":"Merve"}] const c = a.reduce((o, { header, name }, i) => ({ ...o, [ header ]: b[i]?.[name] // use optional-chaining in case it doesn't exist }), {}) console.log(c)

This produces an object.这会产生一个对象。 If you really need that to be a single-element array, just wrap it, ie如果你真的需要它是一个单元素数组,只需包装它,即

const cArray = [ c ] // no idea why

Phil provided a generalized solution already, here is a non-generalized solution maybe easier to understand the basics: Phil 已经提供了一个通用的解决方案,这是一个非通用的解决方案,可能更容易理解基础知识:

 var a = [{ name: 'CreatedDateTime', header: 'Tarih' },{ name: 'Name', header: 'Adi' }] var b = [{ CreatedDateTime:"10.1.2021" },{Name:"Merve"}] var c = {}; c[a[0].header] = b[0][a[0].name] c[a[1].header] = b[1][a[1].name] console.log("c: ", c)

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

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