Convert 1 object thành 1 mảng

mình dùng ajax để call api và trả về response như sau

[{name: "michael", age: 20}, {name: "peter", age:30}]

nhưng type của nó là object và mình muốn add thêm 1 phần tử vào nó, nhưng chưa tìm được cách convert nó sang array. Help me.

dùng hàm push vào object là được mà bạn

tớ thử các kiểu rồi. log ra vẫn không thay đổi

image

3 Likes
var fakeArr = {
 '0': 'zero', '1': 'one', '2': 'two',
 '3': 'three', '4': 'four', '5': 'five',
 length: 6
};

// Error:
// fakeArr.push('six');

var realArr = Array.from(fakeArr);
realArr.push('six');
var iterable = {
  [Symbol.iterator]: function () {
    var iterator = {
      next: function () {
        if (this.__current__ < this.__last__) {
          return { value: this.__current__++, done: false };
        }
        return { done: true };
      }
    };

    Object.defineProperty(iterator, '__current__', {
      value: 0,
      writable: true
    });
    Object.defineProperty(iterator, '__last__', {
      value: 5
    });

    return iterator;
  }
};

// Error:
// iterable.push(6);

var arr = Array.from(iterable);
arr.push(6);
3 Likes
<!DOCTYPE html>
<html>
<head>
	<title>KnockoutJS Simple Example</title>
	<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
	type="text/javascript"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>		
</head>
<body>
	<table>
		<thead>
			<td>age</td>
			<td>name</td>
		</thead>
		<tbody data-bind="foreach: persons">
			<tr>
				<td data-bind="text: age"></td>
				<td data-bind="text: name"></td>
			</tr>
		</tbody>
	</table>
	<script type="text/javascript">
		function viewModel() {
			var self = this;
			self.persons = ko.observableArray();
			$.getJSON("http://localhost:8080/haha/xx", function(data) { 
				self.persons(data);
				console.log(data);
				self.persons.push({name: "xxxx", age: 100});
				console.log(self.persons());
			});
                            //self.persons.push({name: "xxxx", age: 100});
				//console.log(self.persons());
		}
		ko.applyBindings(new viewModel());
	</script>	
</body>
</html>

đấy là code của em. em muốn dung knockoutjs để get dữ liệu từ api rồi thay đổi dữ liệu ấy nhưng nếu em để cái phần thêm 1 phần tử trong block ajax call api thì nó chạy ok, nhưng bỏ ra ngoài block ấy thì nó bị ghi đè, logic, tại sao lại như vậy hả anh.

tìm hiểu về bất đồng bộ trong js bạn sẽ hiểu tại sao! để xử lý trong js có async/await hay callback, cái function phía sau ajax là callback!

2 posts were merged into an existing topic: Topic lưu trữ các post off-topic - version 3

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?