2

I have an array of objects, say the object looks like following:

var row = {
    data: 'test',
   text: 'test'
};

I want to loop through the array and just get the object with text property. What is the best way to do it? So, I want to loop and the object should look like: row = {text: 'test'}

I tried something like below without luck:

arr.forEach(function (item){ //arr is the array of object
     return {text: item.text};
});
1
  • >I want to loop through the array and just get the object with text property -- which one do you want to get? Commented Jul 30, 2015 at 15:35

2 Answers 2

3

Use Array.prototype.map for that:

var arr = [{
    data: 'testData',
   text: 'testText'
}];

var newArr = arr.map(function(item){
    return {text: item.data};
});

The result will look like:

[{ text: 'testData' }]

If you want it to be [ {testText: 'testData' }] then:

var arr = [{
    data: 'testData',
   text: 'testText'
}];

var newArr = arr.map(function(item){
    var obj = {};
    obj[item.text] = item.data;
    return obj;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. Worked like a charm.
0

As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.

var array = [
   {
      text : "text",
      data : "data"
   },
   {
      text : "text1",
      data : "data1"
   }
]

var newArray = array.map(function(item){
    return item.data;
});

your output will look like

 ['text','text1']

1 Comment

That was just an example, I do need more than one key value pair. sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.