How to update object attributes values in knockout.js at once

39 Views Asked by At

How to update object attributes values in knockout.js at once

the way i do is one by one like the example here

self.person = {
  id: ko.observable(),
  name: ko.observable()
};

self.person.id("1");
self.name.id("AAAA");

what i want is something like this

self.person = {
  id: ko.observable(),
  name: ko.observable()
};

var temp = {
id: "1",
name : "AAAA"
}

self.person(temp)

is it possible ?

1

There are 1 best solutions below

2
user3297291 On

Since you tagged the , here's how to do it using ko.mapping.fromJS:

const person = ko.mapping.fromJS({
  id: undefined,
  name: undefined
});

const temp = {
  id: "1",
  name : "AAAA"
}

// Both undefined:
console.log(
  person.name(),
  person.id()
)

ko.mapping.fromJS(temp, person);

// Now set to 1 and AAAA
console.log(
  person.name(),
  person.id()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>

For more information, check out the documentation.