1
var data = [];

data.push({
  Id: 1,
  name: "ONE"
});
data.push({
  Id: 2,
  name: "TWO"
});
data.push({
  Id: 3,
  name: "THREE"
});

data.filter(function(item) {

  if (item.Id == 1) {
    return item.name = display();
  }
});

function display() {
  return "Formatted Text";
}

I am using array filter function to find a value inside array of objects. I am not able to use display() function inside this filter.

Compiler keeps telling display() function is undefined.

3
  • filter returns an array with the filtered items. you need an assignment and just return the result of the check. Commented Nov 23, 2017 at 18:16
  • @NinaScholz could u pls demonstrate? Commented Nov 23, 2017 at 18:20
  • You have other issues in code shown but no reason that display would be undefined Commented Nov 23, 2017 at 18:23

3 Answers 3

3

You could take Array#forEach, because Array#filter returns an array with the filtered items.

It looks like, you want to assign a new value with a condition, so you need no new array.

function display() {
    return "Formatted Text";
}

var data = [{ Id: 1, name: "ONE" }, { Id: 2, name: "TWO" }, { Id: 3, name: "THREE" }];

data.forEach(function(item) {
    if (item.Id === 1) {
        item.name = display();
    }
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, he can find an item by ID and then update the returned item (if any).
1

I think you better need to use findIndex instead of filter like:

const arrIndex = data.findIndex(function(item) {
   return item.Id==1
});

if(arrIndex !== -1) { data[arrIndex] = display(); }

Comments

0

Try this:

var data = [{
    Id: 1,
    name: "ONE"
}, {
    Id: 2,
    name: "TWO"
}, {
    Id: 3,
    name: "THREE"
}];

data.map(function(item) {

    if (item.Id == 1) {
        item.name = display();
    }
    return item;
});

function display() {
    return "Formatted Text";
}

2 Comments

Add an explanation to your answer.
Instead of forEach just I have used map function. filter will filer the data so here map is preferable

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.