简体   繁体   English

如何从打字稿中的对象获取键和值

[英]How to get the key and value from an object in typescript

I got a dictionary pair like {general: "this is the value content"} from a ngForm.我从 ngForm 得到了一个像 {general: "this is the value content"} 这样的字典对。

 <div class="col-10"> <div> <h1>Terms of Use</h1> </div> <form #termForm="ngForm" (ngSubmit)="saveTerm(termForm)"> <div class="col-12"> <div class="d-flex justify-content-between mb-1"> <label for="general" id='general'>General</label> <button>Save General</button> </div> <ckeditor [(ngModel)]="generalContent" #general="ngModel" name="general" [config]="config" [readonly]="false"> </ckeditor> </div> </form> </div>

How can the pair data be saved to separate variables a and b?如何将配对数据保存为单独的变量 a 和 b? a = "general" b = "this is the value content" a = "一般" b = "这是值内容"

If you have the object already stored in a variable, and you plan to only map a single key-value pair to "a" and "b", you could go with:如果您已将对象存储在变量中,并且您计划将单个键值对映射到“a”和“b”,则可以使用:

const obj = { general: "this is the value content" };
const result = Object.entries(obj).map(([k,v]) => ({ a: k, b: v }))[0];
// { a: "general", b: "this is the value content" }

If you have more than a single key-value pair, You can convert the object to an array:如果您有多个键值对,您可以将对象转换为数组:

const terms = {term1: "term1 content", term2: "term2 content"}
const array = Object.entries(terms)
  .map(([key, val]) => [key, val])
  .reduce((a, b) => a.concat(b));
// ["term1", "term1 content", "term2", "term2 content"]

If you want to separate the key-value only in HTML, You can use keyvalue pipe:如果只想在 HTML 中分隔键值,可以使用键值管道:

<div class="col-10">
  <div>
      <h1>Terms of Use</h1>
  </div>
  <form #termForm="ngForm" (ngSubmit)="saveTerm(termForm)">
      <div class="col-12" *ngFor="let term of terms | keyvalue">
          <div class="d-flex justify-content-between mb-1">  
              <label [for]="term.key" [id]="term.key">{{term.key}}</label>
              <button>Save {{term.key}}</button>
          </div>
          <ckeditor        
              [(ngModel)]="term.value"
              #termElem="ngModel"
              [name]="term.key"
              [config]="config"
              [readonly]="false">
          </ckeditor>
      </div>
  </form>
</div>

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

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