Hướng dẫn can i convert string to object javascript? - tôi có thể chuyển đổi chuỗi thành đối tượng javascript không?

Nếu bạn có một chuỗi như foo: 1, bar: 2, bạn có thể chuyển đổi nó thành OBJ hợp lệ với:

str
  .split[',']
  .map[x => x.split[':'].map[y => y.trim[]]]
  .reduce[[a, x] => {
    a[x[0]] = x[1];
    return a;
  }, {}];

Cảm ơn Niggler trong #JavaScript vì điều đó.

Cập nhật với giải thích:

const obj = 'foo: 1, bar: 2'
  .split[','] // split into ['foo: 1', 'bar: 2']
  .map[keyVal => { // go over each keyVal value in that array
    return keyVal
      .split[':'] // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map[_ => _.trim[]] // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  }]
  .reduce[[accumulator, currentValue] => { // reduce[] takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce[] works like map[] in the sense it iterates over an array, and it can be chained upon things like map[],
    // first time through it would say "okay accumulator, accumulate currentValue[0] [which is 'foo'] = currentValue[1] [which is '1']
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}] // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log[obj]

Tài liệu MDN khó hiểu:

  • //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
  • //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Bản demo: //jsbin.com/hiduhijevu/edit?js,console

Function:

const str2obj = str => {
  return str
    .split[',']
    .map[keyVal => {
      return keyVal
        .split[':']
        .map[_ => _.trim[]]
    }]
    .reduce[[accumulator, currentValue] => {
      accumulator[currentValue[0]] = currentValue[1]
      return accumulator
    }, {}]
}

console.log[str2obj['foo: 1, bar: 2']] // see? works!

Chào mừng bạn đến với một hướng dẫn ngắn về cách chuyển đổi một chuỗi thành một đối tượng trong JavaScript. Vâng, để có câu trả lời nhanh -

Hàm JavaScript gốc duy nhất để chuyển đổi một chuỗi thành một đối tượng là JSON.parse[]. Ví dụ, var parsed = JSON.parse['{"foo":"bar"}']. Để chuyển đổi chuỗi của các định dạng khác, nó phải được thực hiện thủ công.

Điều đó bao gồm những điều cơ bản, nhưng chúng ta hãy đi qua một vài ví dụ nữa trong hướng dẫn này - đọc tiếp!

Tôi đã bao gồm một tệp zip với tất cả các mã nguồn ví dụ khi bắt đầu hướng dẫn này, vì vậy bạn không phải sao chép mọi thứ, hoặc nếu bạn chỉ muốn đi thẳng vào.

Trượt nhanh

MỤC LỤC

Tải xuống & ghi chú

Thứ nhất, đây là liên kết tải xuống đến mã ví dụ như đã hứa.

Ghi chú nhanh

Nếu bạn phát hiện ra một lỗi, hãy bình luận bên dưới. Tôi cũng cố gắng trả lời các câu hỏi ngắn, nhưng đó là một người so với toàn bộ thế giới, nếu bạn cần câu trả lời khẩn cấp, vui lòng kiểm tra danh sách các trang web của tôi để nhận trợ giúp lập trình.

Mã hóa ví dụ Tải xuống

Nhấn vào đây để tải xuống mã nguồn, tôi đã phát hành nó theo giấy phép MIT, vì vậy hãy thoải mái xây dựng trên đó hoặc sử dụng nó trong dự án của riêng bạn.

Được rồi, bây giờ chúng ta hãy đi vào các cách khác nhau mà chúng ta có thể tạo các chức năng [hoặc quy trình] để biến một chuỗi thành một đối tượng.

1] Json Parse

1-json.js

// [A] JSON ENCODED STRING
var thestring = '{"Name":"Jon Doe","Email":"","Address":"123 Doe Street"}';

// [B] PARSE JSON
var theobj = JSON.parse[thestring];

/* Name: "Jon Doe",
 * Email: "",
 * Address: "123 Doe Street"
 */
console.log[theobj];

Đối với những người mới bắt đầu chưa nghe về nó - JSON là viết tắt của ký hiệu đối tượng JavaScript. Đơn giản chỉ cần đặt, biến một mảng hoặc đối tượng trong một chuỗi. JSON.stringify[OBJECT] sẽ biến một đối tượng thành một chuỗi được mã hóa JSON, sau đó chúng tôi sử dụng hàm

const obj = 'foo: 1, bar: 2'
  .split[','] // split into ['foo: 1', 'bar: 2']
  .map[keyVal => { // go over each keyVal value in that array
    return keyVal
      .split[':'] // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map[_ => _.trim[]] // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  }]
  .reduce[[accumulator, currentValue] => { // reduce[] takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce[] works like map[] in the sense it iterates over an array, and it can be chained upon things like map[],
    // first time through it would say "okay accumulator, accumulate currentValue[0] [which is 'foo'] = currentValue[1] [which is '1']
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}] // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log[obj]
0 để biến nó trở lại thành một đối tượng.

2] Hướng dẫn sử dụng vòng lặp

2-for.js

[A] CSV STRING
var thestring = "Name,Joe Doe,Email,,Address,234 Doe Street";

// [B] MANUAL PROCESS AND LOOP
var temp = thestring.split[","],
    theobj = {};
for [let i=0; i { // go over each keyVal value in that array
    return keyVal
      .split[':'] // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map[_ => _.trim[]] // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  }]
  .reduce[[accumulator, currentValue] => { // reduce[] takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce[] works like map[] in the sense it iterates over an array, and it can be chained upon things like map[],
    // first time through it would say "okay accumulator, accumulate currentValue[0] [which is 'foo'] = currentValue[1] [which is '1']
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}] // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log[obj]
1. Trước tiên, chúng tôi chia các giá trị bằng cách sử dụng
const obj = 'foo: 1, bar: 2'
  .split[','] // split into ['foo: 1', 'bar: 2']
  .map[keyVal => { // go over each keyVal value in that array
    return keyVal
      .split[':'] // split into ['foo', '1'] and on the next loop ['bar', '2']
      .map[_ => _.trim[]] // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
  }]
  .reduce[[accumulator, currentValue] => { // reduce[] takes a func and a beginning object, we're making a fresh object
    accumulator[currentValue[0]] = currentValue[1]
    // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
    // since reduce[] works like map[] in the sense it iterates over an array, and it can be chained upon things like map[],
    // first time through it would say "okay accumulator, accumulate currentValue[0] [which is 'foo'] = currentValue[1] [which is '1']
    // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
    // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
    return accumulator
  }, {}] // when there are no more things in the array to iterate over, it returns the accumulated stuff

console.log[obj]
2, sau đó ghép chúng lại thành một đối tượng.

3] Chức năng nhập khẩu ”

3-function.js

// [A] THE EXISTING OBJECT
var theobj = {
  // [A1] OBJECT PROPERTIES
  Name: null,
  Email: null,
  Address: null,

  // [A2] IMPORT FROM CSV STRING
  inCSV : function [str] {
    let tempA = str.split[","],
        tempB = {};
    for [let i=0; i

Bài Viết Liên Quan

Chủ Đề