简体   繁体   English

如何将 object 推入数组?

[英]How can I push an object into an array?

I know it's simple, but I don't get it.我知道这很简单,但我不明白。

I have this code:我有这段代码:

// My object
const nieto = {
  label: "Title",
  value: "Ramones" 
}

let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);

If I do this I'll get a simple array:如果我这样做,我会得到一个简单的数组:

["Title", "Ramones"]

I need to create the following:我需要创建以下内容:

[{"01":"Title", "02": "Ramones"}]

How can I use push() to add the object into the nietos array?如何使用push()将 object 添加到nietos数组中?

You have to create an object .您必须创建一个对象 Assign the values to the object.分配给对象。 Then push it into the array:然后将其推入数组:

var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);

Create an array of object like this:像这样创建一个对象数组:

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

First you create the object inside of the push method and then return the newly created array.首先在 push 方法中创建对象,然后返回新创建的数组。

can be done like this too.也可以这样做。

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

Well, ["Title", "Ramones"] is an array of strings.好吧, ["Title", "Ramones"]是一个字符串数组。 But [{"01":"Title", "02", "Ramones"}] is an array of object.但是[{"01":"Title", "02", "Ramones"}]是一个对象数组。

If you are willing to push properties or value into one object, you need to access that object and then push data into that.如果您愿意将属性或值推送到一个对象中,则需要访问该对象,然后将数据推送到该对象中。 Example: nietos[indexNumber].yourProperty=yourValue;示例: nietos[indexNumber].yourProperty=yourValue; in real application:在实际应用中:

nietos[0].02 = "Ramones";

If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.如果您的对象数组已经是空的,请确保它至少有一个对象,或者您要将数据推送到的那个对象。

Let's say, our array is myArray[] , so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing.假设,我们的数组是myArray[] ,所以现在这是空数组,JS 引擎不知道它有什么类型的数据,不是字符串,不是对象,不是数字。 So, we are going to push an object (maybe empty object) into that array.因此,我们要将一个对象(可能是空对象)推送到该数组中。 myArray.push({}) , or myArray.push({""}) . myArray.push({})myArray.push({""})

This will push an empty object into myArray which will have an index number 0 , so your exact object is now myArray[0]这会将一个空对象推送到myArray ,该对象的索引号为0 ,因此您的确切对象现在是myArray[0]

Then push property and value into that like this:然后像这样将propertyvalue推入其中:

myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";

I'm not really sure, but you can try some like this:我不太确定,但你可以试试这样的:

var pack = function( arr ) {
    var length = arr.length,
        result = {},
        i;

    for ( i = 0; i < length; i++ ) {
        result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
    }

    return result;
};

pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

The below solution is more straight-forward.下面的解决方案更直接。 All you have to do is define one simple function that can "CREATE" the object from the two given items.您所要做的就是定义一个简单的函数,该函数可以从两个给定的项目“创建”对象。 Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.然后简单地将此函数应用于具有要为其创建对象并保存在 resultArray 中的元素的两个数组。

var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
    for (var j=0; j<arr1.length; j++) {
        resultArray[j] = new makeArray(arr1[j], arr2[j]);
    }
function makeArray(first,second) {
    this.first = first;
    this.second = second;
}

 let nietos = []; function nieto(aData) { let o = {}; for ( let i = 0; i < aData.length; i++ ) { let key = "0" + (i + 1); o[key] = aData[i]; } nietos.push(o); } nieto( ["Band", "Ramones"] ); nieto( ["Style", "RockPunk"] ); nieto( ["", "", "", "Another String"] ); /* convert array of object into string json */ var jsonString = JSON.stringify(nietos); document.write(jsonString);

Add an object into an array 将对象添加到数组中

 let nietos = []; function nieto(aData) { let o = {}; for ( let i = 0; i < aData.length; i++ ) { let key = "0" + (i + 1); o[key] = aData[i]; } nietos.push(o); } nieto( ["Band", "Ramones"] ); nieto( ["Style", "RockPunk"] ); nieto( ["", "", "", "Another String"] ); /* convert array of object into string json */ var jsonString = JSON.stringify(nietos); document.write(jsonString);

Save your values in array and convert it using stringify将您的值保存在数组中并使用 stringify 进行转换

var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;

var jsonString = JSON.stringify(nietos);

With "push()" method:使用“push()”方法:

let nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});

With "concat()" method:使用“concat()”方法:

let nietos = [];
nietos = nietos.concat({"01": nieto.label, "02": nieto.value});

Using destructuring assignment (ES6)使用解构赋值 (ES6)

  1. Modify the object修改对象
let modifiedObj = {'01': obj.label, '02': obj.value};
  1. Unpack the objects inside the array (in case the array is empty it will still work)解包数组中的对象(如果数组为空,它仍然可以工作)
[...restOfArray] = array; 
  1. Push the modified object to the first index like so:将修改后的对象推送到第一个索引,如下所示:
array = [modifiedObj , ...restOfArray];

 const obj = {label: "Title", value: "Ramones" } let restOfArray, array = [ {'03': 'asd', '04': 'asd'}, {'05': 'asd', '06': 'asd'} ]; let modifiedObj = {'01': obj.label, '02': obj.value}; [...restOfArray] = array; array = [modifiedObj , ...restOfArray]; console.log(array);

If you'd like to push it to the last index just change ...restOfArray to the front.如果您想将其推送到最后一个索引,只需将...restOfArray更改为前面。

array = [...restOfArray, modifiedObj];

This solution can be used when you have more than 2 properties in any object.当您在任何对象中拥有超过 2 个属性时,可以使用此解决方案。

const nieto = {
  label: "Title",
  value: "Ramones" 
}

let nietos = [];

let xyz = Object.entries(nieto)

xyz.forEach((i,j)=>{
    i[0] = `${(j+1).toLocaleString("en-US", {
        minimumIntegerDigits: 2,
        useGrouping: false,
      })}`
})

nietos.push(Object.fromEntries(xyz))

Add an object to an array将对象添加到数组

class App extends React.Component {
  state = {
  value: ""
  };

items = [
  {
    id: 0,
    title: "first item"
  },
  {
    id: 1,
    title: "second item"
  },
  {
    id: 2,
    title: "third item"
  }
];

handleChange = e => {
  this.setState({
    value: e.target.value
  });
};

handleAddItem = () => {
  if (this.state.value === "") return;
  const item = new Object();
  item.id = this.items.length;
  item.title = this.state.value;
  this.items.push(item);
  this.setState({
    value: ""
  });

  console.log(this.items);
};

render() {
  const items = this.items.map(item => <p>{item.title}</p>);
  return (
    <>
      <label>
        <input
          value={this.state.value}
          type="text"
          onChange={this.handleChange}
        />
        <button onClick={this.handleAddItem}>Add item</button>
      </label>
      <h1>{items}</h1>
    </>
  );
}
}

ReactDOM.render(<App />, document.getElementById("root"));

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

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