![](/img/trans.png)
[英]How to get the value of an object in array by key in Typescript
[英]How to get the key and value from an object in typescript
我從 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>
如何將配對數據保存為單獨的變量 a 和 b? a = "一般" b = "這是值內容"
如果您已將對象存儲在變量中,並且您計划僅將單個鍵值對映射到“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" }
如果您有多個鍵值對,您可以將對象轉換為數組:
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"]
如果只想在 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.